Writing a file
Writing to a file is accomplished in the same manner as writing to the console. Using the puts
command with the addition of a file channel descriptor will result in the string provided being written to the channel. The syntax is as follows:
puts -nonewline channel string
How to do it…
Enter the following command:
% set fp [open text.txt a] file5 % puts $fp "Hello Again" % flush $fp
How it works…
The puts
command will write the data contained in string
to the referenced file pointer
. If the optional nonewline
switch is provided the newline character will not be added. Bear in mind that if you are not closing the file following the write action, it is necessary to flush
the channel to complete the write. The channel is automatically flushed when the file pointer is closed or when the application exits.
To check the file, open it with the text editor of your choice. You should see a file that contains the following:
Hello World