gpt4 book ai didi

file - tcl如何读取文件

转载 作者:行者123 更新时间:2023-12-05 00:36:42 27 4
gpt4 key购买 nike

我在正确读取 2 个文件时遇到一些问题:

filetest1.txt 包含:

chocolate
coconut
banana

filetest2.txt 包含:

strawberry
orange

程序:

proc callme {file1 file2} {
set file1 [open $file1 r]
set file2 [open $file2 r]
while {[gets $file1 line1] != -1} {
while {[gets $file2 line2] != -1} {
puts "inside : $line1"
}
puts "outside : $line1"
}
close $file1
close $file2
}
callme filetest1.txt filetest2.txt

输出显示:

inside : chocolate
inside : chocolate
outside : chocolate
outside : coconut
outside : banana

所以我的问题是为什么只有:

inside : chocolate
inside : chocolate

我期望有:

inside : chocolate
inside : chocolate
outside : chocolate
inside : coconut
inside : coconut
outside : coconut
inside : banana
inside : banana
outside : banana

谢谢。

最佳答案

您应该将代码更改为:

proc callme {file1 file2} {
set file1 [open $file1 r]
set file2 [open $file2 r]
while {[gets $file1 line1] != -1} {
seek $file2 0 start
while {[gets $file2 line2] != -1} {
puts "inside : $line1"
}
puts "outside : $line"
}
close $file1
close $file2
}
callme filetest1.txt filetest2.txt

请注意 seek $file2 0 start,它让您在循环的每次迭代中返回到第二个文件的开头。希望这对您有所帮助!

关于file - tcl如何读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18837614/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com