Tcl Files
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 ?-force? name
- Deletes the file named name.
- file dirname name
- Returns the parent directory of the file named name.
- file exists name
- Check for the existence of the file named name. Returns 1 if the file exists, 0 otherwise.
- file join path1 path2 …
- Joins path1, path2, etc. into a new pathname.
- file nativename name
- Returns the platform specific version of the file named name.
- file split name
- Splits the file named name into its individual pathname parts.
- open name ?access? ?permissions?
- Opens a file named name for reading/writing, depending on the access arguments. Returns the channel ID.
- close channel
- Closes channel.
- gets channel varname
- Reads a line from channel and assigns the data to variable varname.
- puts ?-nonewline? ?channel? string
- Writes out string to channel. If channel is not specified, the default output channel is used.
- read ?-nonewline? channel
- Reads all data from channel.
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];