user3035037
user3035037

Reputation: 19

Writing to file in TCL

i have a following code but my report1.out only has last value of k variable. How can I change it so that it writes value of k and then new line and new value.

Will appreciate help.

Code is:

# 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

Upvotes: 0

Views: 33451

Answers (1)

Eric Melski
Eric Melski

Reputation: 16790

You're using w+ as the open mode for the file. Here's a section of the man page for Tcl's open command:

   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.

So, w+ truncates the file if it exists, which is why you get only one line of output. You should use a+ instead, or even just a since you don't actually need to read the file.

Alternatively, you could rewrite your code so that the file is opened only once, outside the loop:

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

This would also improve efficiency by avoiding repeatedly opening/closing the file.

Upvotes: 3

Related Questions