Version 12 of Additional file commands

Updated 2001-12-19 13:08:44

Read a text file into a string:

 proc readfile filename {
    set fp [open $filename]
    set res [read $fp [file size $filename]]
    close $fp
    set res 
 }

Just out of curiosity... would the minimal code below be equivalent, i.e. is the close indeed automatic in this context? -JCW

 proc readfile filename {
    read [open $filename] [file size $filename]
 }

RS: According to man close, "Channels are automatically closed when an interpreter is destroyed and when the process exits." From this I imply they are not closed automatically elsewhere. A handle of a file open for reading can't do much harm, except leak some memory (and may cause the app to run out of available file descriptors...) Anyway, I've applied the simple rule "if you opened it, close it" ;-)

JCW: Yes, ok, but doesn't the file get closed when (and because) the last reference goes away? Or is bytecode compilation affecting this and leading to a kept reference? Inquiring minds want to know... :o)

Vince: There's a reference in the interpreter (as 'file channels' will show). The only way to get rid of this reference is with 'close' (unless you resort to C code).


Touch a file: without modifying the contents, change a file's access time to (now); create it if it doesn't exist, with 0 bytes contents:

 proc touch filename {
    close [open $filename a]
 } ;# after Don Porter in c.l.t, brought here by RS 

Why not just use

        file mtime $filename [clock seconds]

RS In very new versions file mtime can be used with a second argument to set the mtime; but not in 8.2.3.


LV with all the bug fixes that have occurred since Tcl 8.2.3, I hope people upgrade to 8.3.4 soon... RS I am actually running 8.3.4 (even compiled it myself ;-), but my Winhelp is still the 8.2.3 one... But I am not hurried to chase after the latest versions - we install Cygwins here that are still on 8.0.4, so our scripts cannot be too demanding ... Also, file mtime .. works only on existing files. To have the full "touch" functionality (create if not exists), the close [open ...] approach is better.. and shorter (in words) too ;-)

LV: However, the close/open has the downside of not having the real touch functionality of being able to set the modification time to whatever time one wants - which file mtime does have.


file - Arts and crafts of Tcl-Tk programming