Once a file is open, you can read from it and write to it.
puts command to write to a file. If you provide a file identifier,
puts will write to that file.
set file [open /tmp/stuff w] puts $file "Hello World" ;# write to /tmp/stuff
puts writes to the standard output by default. Sometimes it is convenient to refer to the standard output explicitly. You can do that using the predefined file identifier
stdout. (You can also refer to the standard input as
stdin and the standard error as
puts command also accepts the argument
-nonewline, which skips adding a newline to the end of the line.
puts -nonewline $file "Hello World"
If you are writing strings without newlines to a character special file (such as a terminal), the output will not immediately appear because the I/O system buffers output one line at a time. However, there are strings you want to appear immediately and without a newline. Prompts are good examples. To force them out, use the
puts -nonewline $file $prompt flush $file
gets command or
read command to read from a file.
gets reads a line at a time and is good for text files in simple applications.
read is appropriate for everything else.
gets command takes a file identifier and an optional variable name in which to store the string that was read. When used this way, the length of the string is returned. If the end of the file is reached, −1 is returned.
I frequently read through files with the following code. ...