How to read a large file line by line using tcl?

I wrote one piece of code using the while loop, but it takes too much time to read the file in turn. Can anybody help me? my code is:

   set a [open myfile r]              
   while {[gets $a line]>=0} {   
     "do somethig by using the line variable" 
   }
+5
source share
2 answers

The code looks great. It's pretty fast (if you are using a fairly new version of Tcl, historically, there were some minor versions of Tcl that had problems with buffer management) and how you read the line at a time.

This is slightly faster if you can read in large quantities at the same time, but then you need to have enough memory to store the file. There are usually no problems with files containing several million lines; modern computers can handle these things simply:

set a [open myfile]
set lines [split [read $a] "\n"]
close $a;                          # Saves a few bytes :-)
foreach line $lines {
    # do something with each line...
}
+7

, , . , .

https://www.tcl.tk/man/tcl8.5/tutorial/Tcl24.html

#
# Count the number of lines in a text file
#
set infile [open "myfile.txt" r]
set number 0

#
# gets with two arguments returns the length of the line,
# -1 if the end of the file is found
#
while { [gets $infile line] >= 0 } {
    incr number
}
close $infile

puts "Number of lines: $number"

#
# Also report it in an external file
#
set outfile [open "report.out" w]
puts $outfile "Number of lines: $number"
close $outfile
0

All Articles