File 如何使用tcl逐行读取大型文件?

File 如何使用tcl逐行读取大型文件?,file,tcl,File,Tcl,我已经使用while循环编写了一段代码,但是逐行读取文件会花费太多时间。有人能帮我吗? 我的代码: set a [open myfile r] while {[gets $a line]>=0} { "do somethig by using the line variable" } 代码看起来不错。它非常快(如果您使用的是足够新的Tcl版本;历史上,Tcl的一些小版本存在缓冲区管理问题),这就是您每次读取一行的方式 如果你

我已经使用while循环编写了一段代码,但是逐行读取文件会花费太多时间。有人能帮我吗? 我的代码:

   set a [open myfile r]              
   while {[gets $a line]>=0} {   
     "do somethig by using the line variable" 
   }

代码看起来不错。它非常快(如果您使用的是足够新的Tcl版本;历史上,Tcl的一些小版本存在缓冲区管理问题),这就是您每次读取一行的方式

如果你能一次读取更多的数据,速度会快一点,但是你需要有足够的内存来保存文件。在上下文中,几百万行的文件通常没有问题;现代计算机可以很好地处理这类事情:

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

如果它确实是一个大文件,您应该执行以下操作,一次只读取一行。使用您的方法将整个内容读入ram


您也可以通过读取固定大小的文件块(例如,一次读取1MB)来工作,但这样您就不能逐行工作,必须做大量的工作来解决问题。我从来没有见过这样值得努力的情况。文件有多大?有多少行?
#
# 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