File handling
operations like reading from and writing to a file in any programming language
is one of the most commonly used operations.
Writing to a file in Tcl
is straightforward.
In this post, we will
discuss two ways to read a file in Tcl:
Note that the text in
black represents tcl commands. Text in red
represents user-defined variables and comments are in blue.
- set in_file [open palindrome_in.csv
r] ## Opens the
file palindrome_in.csv in read mode
set out_file [open palindrome_out.csv w] ## Opens the file palindrome_out.csv in write mode
set data [read $in_file] ## "data" now has contents of the input file
set lines [split $data "\n"] ## "lines" now contain collection of lines
foreach line $lines { ## Reading each "line" from collection of "lines"
<body of your proc> ## Body of the proc
}
puts $out_file "xyz" ## Printing the desired output in palindrome_out.csv
close $out_file ## Closing the output file
close $in_file ## Closing the input file
Note: Closing both the input and output files is important. If not done, your Tcl shell might return an error "too many open files". Or even worse, the output in the output file might get terminated pre-maturely. - set in_file [open palindrome_in.csv
r] ##
Opens the file palindrome_in.csv in read mode
set out_file [open palindrome_out.csv w] ## Opens the file palindrome_out.csv in write mode
while { [gets $in_file line] >= 0 } { ## Note that here "line" is not a user-defined variable
<body of your proc> ## Body of the proc
}
puts $out_file "xyz" ## Printing the desired output in palindrome_out.csv
close $out_file ## Closing the output file
close $in_file ## Closing the input file
What's the difference between the two?
Well, not much, if the size of your input file in small. However, if it is a
big file (for example: SDF files, where the file maybe as big as 1 GB!!), you
might prefer using the second method.
In the first method, the user-defined variable lines contain all the lines of the file in form of a collection. If file is too big, this collection would be too big and one variable will have to hold this fairly big data till your script is working. This might lead to "stack-overflow error".
This problem is alleviated in the second way where you are reading each line on the go.
Sign up here with your email
ConversionConversion EmoticonEmoticon