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.
- 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.
set filename {C:\My_files\readme.txt};
C:\My_files\readme.txt
file join [file nativename $filename];
C:/My_files/readme.txt
set filename "C:\\My_files\\readme.txt";
C:\My_files\readme.txt
file join [file nativename $filename];
C:/My_files/readme.txt
file exists "C:/My_files/readme.txt";
1
set fileID [file open "C:/My_files/readme.txt" r];
puts "$fileID";
Tcl returns the selected fileID.
set fileID [file open "C:/My_files/readme.txt" w+];
puts "$fileID";
Tcl returns the selected fileID.
set fileID [file open "C:/My_files/readme.txt" a+];
puts "$fileID";
Tcl returns the selected fileID.
set filename [encoding convertto euc-jp $filename];