Since Tcl/Tk scripts run on a variety of platforms, and there are so many use cases for accessing files, Tcl provides many commands for file manipulation.
The following table contains some commonly used Tcl file commands and a summary of their usage. For more in-depth explanations and a complete listing, referred to http://www.tcl.tk/man/ or to a Tcl/Tk handbook.
file delete
Deletes the file named .
file dirname
Returns the parent directory of the file named .
file exists
Check for the existence of the file named name. Returns 1 if the file exists, 0 otherwise.
file join
Joins , , etc. into a new pathname.
file nativename
Returns the platform specific version of the file named .
file split
Splits the file named name into its individual pathname parts.
open
Opens a file named name for reading/writing, depending on the arguments. Returns the channel ID.
close
Closes .
gets
Reads a line from and assigns the data to variable .
puts
Writes out to . If is not specified, the default output channel is used.
read
Reads all data from .
One item to note is that Unix uses a forward slash / as a directory separator and Windows uses a backward slash \ as a directory separator. The backward slash in Tcl is a special escape character. So on both Windows and Unix, Tcl uses / as the directory separator.
It is possible to convert a filename to the Tcl format. Notice the curly braces around the filename so that the \ character isn’t interpreted as the escape character.
set filename {C:\My_files\readme.txt};
C:\My_files\readme.txt
file join [file nativename $filename];
C:/My_files/readme.txt
While not recommended, it is also possible to escape the \ character for Windows pathnames by using another \ preceding each pathname part.
set filename "C:\\My_files\\readme.txt";
C:\My_files\readme.txt
file join [file nativename $filename];
C:/My_files/readme.txt
If the file readme.txt exists in C:/My_files, the file exists command will return a value of 1.
file exists "C:/My_files/readme.txt";
1
A file can be opened for reading.
set fileID [file open "C:/My_files/readme.txt" r];
puts "$fileID";
Tcl returns the selected fileID.
A file can be opened for reading and writing, truncating the file or creating it if it does not exist.
set fileID [file open "C:/My_files/readme.txt" w+];
puts "$fileID";
Tcl returns the selected fileID.
A file can be opened for reading and writing, appending data to the end of the file.
set fileID [file open "C:/My_files/readme.txt" a+];
puts "$fileID";
Tcl returns the selected fileID.
To support customers that use Japanese file names, the encoding command enables multi-bit characters.
set filename [encoding convertto euc-jp $filename];