I’ve got from sqlite3 value that could be written in hex like "0x0D 0x0A". Yes, it’s (CR) and (LF). I want to know a length of data i’ve got. But command "string length" returns 1, not 2. "string bytelength" returns 1 too. How can I get correct length of data in bytes?
It’s a simple example. In real program I’ve got different text data from sqlite with unknown encoding. All I need is to get length of data in bytes. But every (CR)(LF) in text are counting as 1 byte.
Examples of getting data from sqlite and file:
sqlite dbcmd messages.db
set t [dbcmd message from messages limit 1,1]
string length $t
set f [open test.txt r]
set t [read $f]
string length $t
(Windows 7, ActiveTcl 8.6.4, tclkit 8.6.6)
By default, Tcl transforms CR-LF sequences in files being read into simple LF characters. This is usually useful, as it simplifies ordinary text processing in scripts greatly. However, if want the exact values then you can use fconfigure to put the channel into an alternate processing mode. For example, changing the channel's -translation setting to lf (from auto) will make all carriage-returns be preserved (and line-feeds too).
set f [open test.txt r]
fconfigure $f -translation lf
set t [read $f]
string length $t
There are other settings that could — in general — affect what you get, particularly the -eofchar and -encoding options. The -eofchar is usually EOF (i.e., the character associated with Ctrl+Z) and the -encoding is a system-specific value that depends on things like what your platform is and what your locale is. If you want to really work with binary data, i.e., get just the bytes, you can set the -translation option to binary, which sets everything up right for handling binary data. There's a shorthand for that common option in the open command:
set f [open test.txt rb]; # ««« “b” flag in open mode
set t [read $f]
string length $t
If you do get the bytes and want to get characters from them at some point, the encoding convertfrom command is the tool you'll need. Remember, characters and bytes are not the same thing. That had to be given up in order to allow people to use more characters than there are values expressible in a byte.
Related
I'm experimenting with coding a very small application-specific local server in Tcl and don't understand the proper method of determining Content-length. I read that it is bytes or decimal number of octets.
In the code below, [file size "index.html"] returns the correct length such that the browser read/loads all of the content; but [string bytelength $html] is too small and the browser does not read to the end.
Why is this and is there a better method? Thank you.
if { $op eq "GET" } {
if { $arg eq "/" } {
set fp [open "index.html" r]
set html [read $fp]
set resp "HTTP/1.1 200 OK\n"
append resp "Connection: Keep-Alive\n"
append resp "Content-Type: text/html; charset: utf-8\n"
append resp "Content-length: [file size "index.html"]\n\n"
#append resp "Content-length: [string bytelength $html]\n\n"
append resp $html
puts stdout $resp
puts $so $resp
close $fp
unset html resp
}
# Remainder of if $arg
}
The result of file size is the number of bytes that the file takes up on disk, and is exactly the number reported by the OS. (It's also the offset you'd be at if you opened the file and seeked to the end.)
If you were to read the file in in binary mode, the string length of what you read would be the same as the file size. When the file is read in (default) text mode it's different because it depends on the encoding that the file is read with; encodings like UTF-8 can use multiple bytes to describe a character and string length reports the number of characters in a string.
The string bytelength command reports the number of bytes used by the data when it is encoded using Tcl's internal encoding (which is rather similar to UTF-8 but not exactly; there are specific denormalizations). That encoding is not normally exposed to the outside world, and is only really of interest to C extensions. Of course, those C extensions can get the length of a string for themselves easily anyway: it's produced (as an OUT parameter because the string itself is the return value) by Tcl_GetStringFromObj() so string bytelength isn't very useful. Indeed, I've only ever found one (1) legitimate use for it, and a better job of integration work with that extension would have got rid of it.
The value reported by string bytelength is not the amount of storage currently used by a value, but rather just (closely related to, by a static difference) the amount of storage used by the standard “string” interpretation. If the value has any other (“internal”) representation as well, which is common (numbers, binary data, true-unicode data, lists, dictionaries, command names, channel handlers, executable code, all those may have additional representation data) then that is not counted.
In your case, you want to open the file in binary mode and use that. And also do this:
set filename "index.html"
set fp [open $filename rb]; # NB: rb — b is for BINARY; this is important
set size [file size $filename]
# HTTP spec says headers are ISO 8859-1 and CRLF-separated
fconfigure $so -encoding iso8859-1 -translation crlf
set headers ""
append headers "HTTP/1.1 200 OK\n"
append headers "Connection: Keep-Alive\n"
# Detecting the content type of a file is its own chunk of complexity
append headers "Content-Type: text/html; charset: utf-8\n"
append headers "Content-length: $size\n"
puts stdout $headers
puts $so $headers
# Ship the data in binary mode; fcopy is VERY efficient
fconfigure $so -translation binary
fcopy $fp $so -size $size
close $fp
Writing HTTP messages to the console is a bit messy because of the mixed encoding used; it's not normally a good idea to write the body of a file. But for debugging you would do:
set data [read $fp]
puts stdout $data
# Additional -nonewline to not add a line terminator
puts -nonewline $so $data
However, the fcopy command (also called chan copy in newer Tcl as part of a command systematization effort) is much more efficient when moving binary data from one place to another. The only way we could make it significantly more efficient would be to move the copy into the OS kernel.
tl;dr: You don't want to use string bytelength. What it does is subtly not useful.
Below there is a trivial script writing a byte to a file:
set wf [open "test.bin" "w"]
set int_result 0x80
puts -nonewline $wf [binary format c [expr {$int_result}]]
close $wf
exit
Surprisingly, the file will contain 0x3F, not 0x80.
Can anybody explain what is happening?
Thanks a lot,
Dmitry
Tcl prefers to read and write text files by default, which means it does a number of transformations on the data for you both going into Tcl and going out to a file. When working with binary data, you want these switched off. Either use wb instead of w in the call to open (just like in C stdio's fopen() call), or use fconfigure to put the channel into binary mode after opening it.
set wf [open "test.bin" wb]
set wf [open "test.bin" w]
# It's the -translation option for historical/backward-compatibility reasons
fconfigure $wf -translation binary
They're equivalent; the b makes open call (the implementation of) fconfigure internally to set exactly that option.
Quick fix: use
open test.bin wb
to open the file in binary mode.
I have the following code:
set myfile "the path to my file"
set fsize [file size $myfile]
set fp [open $myfile r]
fconfigure $fp -translation binary
set data [read $fp $fsize]
close $fp
puts $fsize
puts [string bytelength $data]
And it shows that the bytes read are different from the bytes requested. The bytes requested match what the filesystem shows; the actual bytes read are 22% more (requested 29300, got 35832). I tested this on Windows, with Tcl 8.6.
Use string length. Don't use string bytelength. It gives the “wrong” answers, or rather it answers a question you probably don't want to ask.
More Depth
The string bytelength command returns the length in bytes of the data in Tcl's internal almost-UTF-8 encoding. If you're not working with Tcl's C API directly, you really have no sensible use for that value, and C code is actually pretty able to get the value without that command. For ASCII text, the length and the byte-length are the same, but for binary data or text with NULs or characters greater than U+00007F (the Unicode character that is equivalent to ASCII DEL), the values will differ. By contrast, the string length command knows how to handle binary data correctly, and will report the number of bytes in the byte-string that you read in. We plan to deprecate the string bytelength command, as it turns out to be a bug in someone's code almost every time they use it.
(I'm guessing that your input data actually has 6532 bytes outside the range 1–127 in it; the other bytes internally use a two-byte representation in almost-UTF-8. Fortunately, Tcl doesn't actually convert into that format until it needs to, and instead uses a compact array of bytes in this case; you're forcing it by asking for the string bytelength.)
Background Information
The question of “how much memory is actually being used by Tcl to read this data” is quite hard to answer, because Tcl will internally mutate data to hold it in the form that is most efficient for the operations you are applying to it. Because Tcl's internal types are all precisely transparent (i.e., conversions to and from them don't lose information) we deliberately don't talk about them much except from an optimisation perspective; as a programmer, you're supposed to pretend that Tcl has no types other than string of unicode characters.
You can peel the veil back a bit with the tcl::unsupported::representation command (introduced in 8.6). Don't use the types for decisions on what to do in your code, as that is really not something guaranteed by the language, but it does let you see a lot more about what is really going on under the covers. Just remember, the values that you see are not the same as the values that Tcl's implementation thinks about. Thinking about the values that you see (without that magic command) will keep you thinking about things that it is correct to write.
I'm trying to implement a tcl script which reads a text file, and masks all the sensitive information (such as passwords, ip addresses etc) contained it and writes the output to another file.
As of now I'm just substituting this data with ** or ##### and searching the entire file with regexp to find the stuff which I need to mask. But since my text file can be 100K lines of text or more, this is turning out to be incredibly inefficient.
Are there any built in tcl functions/commands I can make use of to do this faster? Do any of the add on packages provide extra options which can help get this done?
Note: I'm using tcl 8.4 (But if there are ways to do this in newer versions of tcl, please do point me to them)
Generally speaking, you should put your code in a procedure to get best performance out of Tcl. (You have got a few more related options in 8.5 and 8.6, such as lambda terms and class methods, but they're closely related to procedures.) You should also be careful with a number of other things:
Put your expressions in braces (expr {$a + $b} instead of expr $a + $b) as that enables a much more efficient compilation strategy.
Pick your channel encodings carefully. (If you do fconfigure $chan -translation binary, that channel will transfer bytes and not characters. However, gets is not be very efficient on byte-oriented channels in 8.4. Using -encoding iso8859-1 -translation lf will give most of the benefits there.)
Tcl does channel buffering quite well.
It might be worth benchmarking your code with different versions of Tcl to see which works best. Try using a tclkit build for testing if you don't want to go to the (minor) hassle of having multiple Tcl interpreters installed just for testing.
The idiomatic way to do line-oriented transformations would be:
proc transformFile {sourceFile targetFile RE replacement} {
# Open for reading
set fin [open $sourceFile]
fconfigure $fin -encoding iso8859-1 -translation lf
# Open for writing
set fout [open $targetFile w]
fconfigure $fout -encoding iso8859-1 -translation lf
# Iterate over the lines, applying the replacement
while {[gets $fin line] >= 0} {
regsub -- $RE $line $replacement line
puts $fout $line
}
# All done
close $fin
close $fout
}
If the file is small enough that it can all fit in memory easily, this is more efficient because the entire match-replace loop is hoisted into the C level:
proc transformFile {sourceFile targetFile RE replacement} {
# Open for reading
set fin [open $sourceFile]
fconfigure $fin -encoding iso8859-1 -translation lf
# Open for writing
set fout [open $targetFile w]
fconfigure $fout -encoding iso8859-1 -translation lf
# Apply the replacement over all lines
regsub -all -line -- $RE [read $fin] $replacement outputlines
puts $fout $outputlines
# All done
close $fin
close $fout
}
Finally, regular expressions aren't necessarily the fastest way to do matching of strings (for example, string match is much faster, but accepts a far more restricted type of pattern). Transforming one style of replacement code to another and getting it to go really fast is not 100% trivial (REs are really flexible).
Especially for very large files - as mentioned - it's not the best way to read the whole file into a variable. As soon as your system runs out of memory you can't prevent your app crashes. For data that is separated by line breaks, the easiest solution is to buffer one line and process it.
Just to give you an example:
# Open old and new file
set old [open "input.txt" r]
set new [open "output.txt" w]
# Configure input channel to provide data separated by line breaks
fconfigure $old -buffering line
# Until the end of the file is reached:
while {[gets $old ln] != -1} {
# Mask sensitive information on variable ln
...
# Write back line to new file
puts $new $ln
}
# Close channels
close $old
close $new
I can't think of any better way to process large files in Tcl - please feel free to tell me any better solution. But Tcl was not made to process large data files. For real performance you may use a compiled instead of a scripted programming language.
Edit: Replaced ![eof $old] in while loop.
A file with 100K lines is not that much (unless every line is 1K chars long :) so I'd suggest you read the entire file into a var and make the substitution on that var:
set fd [open file r+]
set buf [read $fd]
set buf [regsub -all $(the-passwd-pattern) $buf ****]
# write it back
seek $fd 0; # This is not safe! See potrzebie's comment for details.
puts -nonewline $fd $buf
close $fd
I am using a tcl script which takes a movie file trace and convert it into binary file which is further used by the application agent in ns-2. Here is the code snippet of the script which converts the movie file trace into binary file:
set original_file_name Verbose_Silence_of_the_Lambs_VBR_H263.dat
set trace_file_name video.dat
set original_file_id [open $original_file_name r]
set trace_file_id [open $trace_file_name w]
set last_time 0
while {[eof $original_file_id] == 0} {
gets $original_file_id current_line
if {[string length $current_line] == 0 ||
[string compare [string index $current_line 0] "#"] == 0} {
continue
}
scan $current_line "%d%s%d" next_time type length
set time [expr 1000*($next_time-$last_time)]
set last_time $next_time
puts -nonewline $trace_file_id [binary format "II" $time $length]
}
close $original_file_id
close $trace_file_id
But when I used this created video.dat file further for traffic generation used by application agent I got the following error:
Bad file siz in video.dat
Segmenatation fault
Kindly have a loot at this. what is the meaning of binary format "II" in the code. as I have not found it mentioned in tcl-binary(n) documentation or is it outdated and not supported now.
The problem is probably that you don't open your file in binary mode.
Change
set trace_file_id [open $trace_file_name w]
to
set trace_file_id [open $trace_file_name wb]
Otherwise Tcl will change the output, e.g. replaces \n with \r\n on windows.
(And for byte values > 127 it will be treated as unicode code point, then converted to your system encoding and thereby messing up your entire binary stuff)
While such things are fine for text files, it generates problems with binary files.
Fortunately only a single character is needed to fix that: b as modifier for open
Edit: I just looked up in the change list for Tcl, the b modifier for open was added with 8.5. I usually only use 8.5 or 8.6, so if you are using an older version of Tcl, add the following line after the open:
fconfigure $trace_file_id -translation binary
The b modifier is just a shortcut for that.