Quite simple. Here's an example:
Code:
# Open a file for writing. We'll assume that
# the file doesn't already exist. The return
# value of the open command is a file
# descriptor that we use as an argument for
# subsequent manipulation of the file.
set fid [open temp.txt w]
# Now, use puts commands to write data to
# the file. Tcl automatically determines the
# proper end-of-line convention for the
# operating system we're using.
puts $fid "Here's the first line."
puts -nonewline $fid "Here's a second line "
puts $fid "written in two separate chunks."
# Close the file when you're done.
close $fid
Note that opening a file in "w" mode creates a file if it doesn't already exist, and
deletes the contents of a file if it already exists. If you want to
append to the end of an existing file, open it with the "a" mode.
To read from the file,
open it for read access, then use the
gets command to read a line at a time:
Code:
set fid [open temp.txt r]
# gets reads a line from the file indicated
# and stores the characters read (minus the
# end-of-line characters) in the variable
# provided. The return value of gets is the
# number of characters read, not including
# the end-of-line characters, or -1 if it
# reaches the end of file.
while {[gets $fid chars] >= 0} {
puts "Read line: $chars"
}
close $fid
That's enough to get you started. For more information, there are quite a few pages on the Tcl'ers Wiki (
that deal with file I/O. You might want to start with "How do I read and write files in Tcl,"
and then follow the various links for more details. - Ken Jones, President
Avia Training and Consulting
866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax