Tcl variable size limit

I am writing a Tcl script to be used on an embedded device. The variable value in this script will come from a text file in the system. I am worried that if the source file is too large, it may cause the device to crash, as there may not be enough memory to store the entire file. I wonder if it is possible to limit the size of a variable, so when a variable is supplied, it does not exhaust the entire memory.

In addition, if it is possible to limit the size of the variable, will it still be filled with as much information as possible from the source file, even if the entire file cannot be transferred to the variable?

+4
source share
2 answers

You can limit the size of the variable by specifying the number of characters to read from the file. For instance:

set f [open file.dat r] set var [read $f 1024] 

This code will read up to 1024 characters from the file (you will get less than 1024 characters if the file is shorter than this, of course).

+7
source

ISTR, the string size limit of any variable in v8.5 is limited to 2 GiB. But, as Eric has already said, in your situation you should not blindly store the file in a variable, but rather process the contents of the file in chunks or at least first estimate its size using file stat and then read it if the size is ok (but note that this approach, of course, contains a race condition, since the file may grow between validation and reading, but in your case this may or may not be a problem).

+3
source

All Articles