Version 1 of Creating Temporary Files

Updated 2002-02-16 17:35:48

Purpose: Show how to create a temp file.

DL


Tcl doesn't have a built-in command to create a temporary file and there are no built-in variables for temp directories, so you have to do a little work.

Best is to figure out the temp directory separately. Then you can create multiple files in it.

 switch $tcl_platform(platform) {
    unix {
        set tmpdir /tmp
    } macintosh {
        set tmpdir $env(TRASH_FOLDER)  ;# a better place?
    } default {
        set tmpdir [pwd]
        catch {set tmpdir $env(TMP)}
        catch {set tmpdir $env(TEMP)}
    }
 }

If you just want one temp file:

 set filename [file join $tmpdir [pid]]

If you want multiple tmpfiles, consider appending things like the application name, counter, time stamp, etc. For example:

 set file [file join $tmpdir $appname.[pid].[incr ::globalCounter]]

DKF - Or create in a subdirectory/subfolder

 if {![file exists [file join $tmpdir [pid]]]} {
    file mkdir [file join $tmpdir [pid]]
 }
 set file [file join $tmpdir [pid] [incr ::globalCounter]]

Michael Schlenker - Be aware of potential race conditions while opening temp files. The linux secure programming howto has some nice examples for the linux platform: http://www.linuxdoc.org/HOWTO/Secure-Programs-HOWTO/avoid-race.html

To be sure to get a new tempfile (and not some evil symlink) try something like:

set access list RDWR CREAT EXCL TRUNC set perm 0600 if {catch {open $file $access $perm} fid} {