tcl supports file handling with the help of the built in commands open, read, puts, gets, and close.
a file represents a sequence of bytes, does not matter if it is a text file or binary file.
opening files
tcl uses the open command to open files in tcl. the syntax for opening a file is as follows −
open filename accessmode
here, filename is string literal, which you will use to name your file and accessmode can have one of the following values −
| sr.no. | mode & description |
|---|---|
| 1 |
r opens an existing text file for reading purpose and the file must exist. this is the default mode used when no accessmode is specified. |
| 2 |
w opens a text file for writing, if it does not exist, then a new file is created else existing file is truncated. |
| 3 |
a opens a text file for writing in appending mode and file must exist. here, your program will start appending content in the existing file content. |
| 4 |
r+ opens a text file for reading and writing both. file must exist already. |
| 5 |
w+ opens a text file for reading and writing both. it first truncate the file to zero length if it exists otherwise create the file if it does not exist. |
| 6 |
a+ opens a text file for reading and writing both. it creates the file if it does not exist. the reading will start from the beginning, but writing can only be appended. |
closing a file
to close a file, use the close command. the syntax for close is as follows −
close filename
any file that has been opened by a program must be closed when the program finishes using that file. in most cases, the files need not be closed explicitly; they are closed automatically when file objects are terminated automatically.
writing a file
puts command is used to write to an open file.
puts $filename "text to write"
a simple example for writing to a file is shown below.
#!/usr/bin/tclsh set fp [open "input.txt" w+] puts $fp "test" close $fp
when the above code is compiled and executed, it creates a new file input.txt in the directory that it has been started under (in the program's working directory).
reading a file
following is the simple command to read from a file −
set file_data [read $fp]
a complete example of read and write is shown below −
#!/usr/bin/tclsh set fp [open "input.txt" w+] puts $fp "test" close $fp set fp [open "input.txt" r] set file_data [read $fp] puts $file_data close $fp
when the above code is compiled and executed, it reads the file created in previous section and produces the following result −
test
here is another example for reading file till end of file line by line −
#!/usr/bin/tclsh
set fp [open "input.txt" w+]
puts $fp "test\ntest"
close $fp
set fp [open "input.txt" r]
while { [gets $fp data] >= 0 } {
puts $data
}
close $fp
when the above code is compiled and executed, it reads the file created in previous section and produces the following result −
test test