我有以下代码,但我的report1.out仅具有k变量的最后一个值。我如何更改它,以便它写入k的值,然后写入新行和新值。
将不胜感激。
# Create a procedure
proc test {} {
set a 43
set b 27
set c [expr $a + $b]
set e [expr fmod($a, $b)]
set d [expr [expr $a - $b]* $c]
puts "c= $c d= $d e=$e"
for {set k 0} {$k < 10} {incr k} {
set outfile1 [open "report1.out" w+]
puts $outfile1 "k= $k"
close $outfile1
if {$k < 5} {
puts "k= $k k < 5, pow = [expr pow ($d, $k)]"
} else {
puts "k= $k k >= 5, mod = [expr $d % $k]"
}
}
}
# calling the procedure
test
您正在使用w+
该文件的打开模式。这是Tclopen
命令的手册页中的一部分:
r Open the file for reading only; the file must already exist. This is the
default value if access is not specified.
r+ Open the file for both reading and writing; the file must already exist.
w Open the file for writing only. Truncate it if it exists. If it does not
exist, create a new file.
w+ Open the file for reading and writing. Truncate it if it exists. If it
does not exist, create a new file.
a Open the file for writing only. If the file does not exist, create a new empty
file. Set the file pointer to the end of the file prior to each write.
a+ Open the file for reading and writing. If the file does not exist, create a
new empty file. Set the initial access position to the end of the file.
因此,w+
如果文件存在则将其截断,这就是为什么只获得一行输出的原因。您应该a+
改用它,甚至只是a
因为实际上不需要读取文件而使用。
或者,您可以重写代码,以便在循环外仅将文件打开一次:
set outfile1 [open "report1.out" w+]
for {set k 0} {$k < 10} {incr k} {
puts $outfile1 "k= $k"
if {$k < 5} {
puts "k= $k k < 5, pow = [expr pow ($d, $k)]"
} else {
puts "k= $k k >= 5, mod = [expr $d % $k]"
}
}
close $outfile1
通过避免重复打开/关闭文件,这也将提高效率。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句