在TCL中写入文件

时间:2013-11-26 05:45:43

标签: tcl

我有以下代码,但我的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

1 个答案:

答案 0 :(得分:2)

您使用w+作为文件的开放模式。以下是Tcl open命令的手册页的一部分:

   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

这也可以通过避免重复打开/关闭文件来提高效率。