跳线问题
以下代码跳过奇数行,例如 1,3,5,7,9......必须完成才能使用此代码从文件中获取所有行
set in [filename r]
seek $in 0 start
while { [gets $in line] != -1 } {
gets $in line
puts $line
}
The following code is skipping odd lines like 1,3,5,7,9......wat has to be done to get all lines from a file using this code
set in [filename r]
seek $in 0 start
while { [gets $in line] != -1 } {
gets $in line
puts $line
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在条件中和循环体中执行一次
gets $in line
;结果,在条件中读取的行会丢失。您可能想删除循环体中的那个。You're doing
gets $in line
once in the condition and once inside the loop body; the line read in the condition gets lost as a result. You probably want to remove the one in the loop body.您已使用 gets 两次,这就是为什么您只获得奇数行
其他解决方案:
我更喜欢使用 read 函数来读取文件的全部内容,然后逐行处理这些内容,而不是使用 gets。因此,我们可以通过将文件作为行列表来完全控制文件操作
set fileName [lindex $argv 0]
catch {set fptr [open $fileName r]} ;
set content [read $fptr] ;#读取文件内容
close $fptr ;关闭文件,因为已经读取了文件
set splitCont [split $contents "\n"] ;#在新行上分割文件内容
splitCont 是列表其中有文件行作为单独的元素
You have used gets twice that is why you are getting only the odd lines
Other solution:
Instead of using gets I prefer using read function to read the whole contents of the file and then process those line by line. So we are in complete control of operation on file by having it as list of lines
set fileName [lindex $argv 0]
catch {set fptr [open $fileName r]} ;
set contents [read $fptr] ;#Read the file contents
close $fptr ;Close the file since it has been read now
set splitCont [split $contents "\n"] ;#Split the files contents on new line
splitCont is the list which has has lines of the file as individual elements