The C stdio package has two function calls related to the creation of temporary files: tmpFile and tmpnam. The Glib too has similar functions in its api such as g_mkstemp, g_file_open_tmp and so on. For someone programming in C, both of these approaches are excellent resources but someones scripting in Tcl more suitable approaches can be taken these C procedures will require a significant amount code to produce an effective binding which, may not offer worthwhile advantages.
The inclusion of a new command gnocl::tmpFile into to the core offers a convenient way of producing unique filenames. The command takes a single argument, an optional prefix, and returns a unique name with a randomized suffix.
If a prefix is specified:
puts [gnocl::tmpFile aaa]
/tmp/aaa.SYzqiJQA8Eeg4GZC1eDb
puts [gnocl::tmpFile bbb]
/tmp/bbb.VIT88L2zjeynnHn5dVfH
/tmp/ccc.3IkQqXjYtwDowshdjjCc
Without a prefix, the defaul 'TclScript' will be used.
puts [gnocl::tmpFile]
/tmp/TclScript.RcrXWEALx2ZDuS3DITli
If a greater level of control in need in the event of opening multiple temporary files then something along the line of the following procs may be of use.
proc tmp:open {} {
set fname [gnocl::tmpFile]
set fp [open $fname w]
lappend ::tmp:files $fp $fname
return $fp
}
proc tmp:files {} {
return [set ::tmp:files]
}
proc tmp:close {fp} {
close $fp
set ::tmp:files [dict remove [set ::tmp:files] $fp]
}
proc tmp:closeAll {} {
dict for {k v} [set ::tmp:files] { close $k }
set ::tmp:files ""
}
proc tmp:unclosed {} {
return [dict keys [set ::tmp:files]]
}
set FP1 [tmp:open]
puts $FP1
set FP2 [tmp:open]
puts [tmp:files]
puts [tmp:unclosed]
tmp:close $FP2
puts [tmp:unclosed]
tmp:closeAll
puts [tmp:unclosed]
Comments