File I/O

There is a comprehensive set of commands for file manipulation. We will cover only the some of the more important ones here.

To open a file the open command is used:

     open name ?access?
     

where name is a string containing the filename, and the option access parameter contains a string of access flags, in the UNIX style. The return result is a handle to the open file.

If access is not present then the access permissions default to "r", which means open for reading only. The command returns a file handle that can be used with other commands. An example of the use of the open command is

     set fid [open "myfile" "r+"]
     

which means open the file myfile for both reading and writing and set the variable fid to the file handle returned.

To close a file simply use

     close fileId
     

For example,

     close $fid
     

will close the file that has the file handle stored in the variable fid.

To read from a file, the read command is used:

     read fileId numBytes
     

which reads numBytes bytes from the file attached to file handle fileId, and returns the bytes actually read.

To read a single line from a file use gets:

     gets fileId ?varName?
     

which reads a line from the file attached to file handle fileId but chops off the trailing newline. If variable varName is specified then the string read in is stored there and the number of bytes is returned by the command. If the variable is not specified, then the command returns the string only.

To write to a file, use puts:

     puts ?-nonewline? ?fileId? string
     

which outputs the string string. If the file handle fileId is present then the string is output to that file; otherwise, it is printed on stdout. If the switch -nonewline is present then a trailing newline is not output.

To check if the end of a file has been reached, use eof:

     eof fileId
     

which, given a file handle fileId returns 1 if the end has been reached, and 0 otherwise.

The are a host of other commands over files and processes, which we will not go into here.

(For extra information on file I/O commands, refer to the Tcl manual pages.)