filetcltk-toolkittcltk2

how to update tcl variable value in file using tcl?


I have 2 tcl file, in data.tcl file i am keeping flag bits and test.tcl file work based on the flag value . I need to reset the flag value in data.tcl after every test . could you please help me to do the same. I tried the following code but its not working

data.tcl file contains flag variable:

set mac 1 
set xmac 0 
set fea 0 

test.tcl script file which has a function to set flag values to 1 or 0 :

  set testcase mac 
  set fp [open "data.tcl" r+] 

  while { [gets $fp data] >= 0 } { 
    set var $data 
    if { [lindex $var 1] == $testcase } { 
       set fp1 [open "data.tcl" w+] 
       while { [gets $fp1 data1] >= 0 } { 
            set var1 $data1 
            if { [lindex $var1 1] == $testcase } { 
            set [lindex $var1 2] 0 
            } 
        close $fp1 
     } 

  close $fp 
   }   
 } 

close $fp 

I have tried the above code but I am not able to update the value of the variable. Please do help on this.

I am writing automation script, where test runs if the particular flag bit is set to one in data.tcl file. After completing the first task, I need to reset the MAC flag value to 0 and I need to set xmac flag file 1 and remaining flags to 0.

before running test script flag values in data.tcl

set mac 1 
set xmac 0 
set fea 0 
set fea1 0 

after 1st run: expected content of data.tcl file:

  set mac 0 
  set xmac 1 
  set fea 0 
  set fea1 0 

after 2nd run: expected content of data.tcl file:

  set mac 0 
  set xmac 0 
  set fea 1 
  set fea1 0 

after 3rd run: expected content of data.tcl file:

  set mac 0 
  set xmac 0 
  set fea 0 
  set fea1 1 

Hope you guys got my requirement.


Solution

  • Opening the file with the w+ flag doesn't mean the values in the file will change if you simply set a few value (and set [lindex $var1 2] 0 is likely not doing what you think it's doing). You have to puts the new value(s). I'd advise putsing the modified content to a different file and then rename it. Something like this possibly:

    set testcase mac 
    set fp [open "data.tcl" r]
    set fp1 [open "data_temp.tcl" w]
    
    while {[gets $fp data] >= 0} { 
      if {[lindex $data 1] == $testcase} {
        # Change this line's 2nd element to 0
        lset data 2 0
      }
      # Write the line to the temp file
      puts $fp1 $data
    }
    
    close $fp
    close $fp1
    
    # Delete the old file
    file delete -force data.tcl
    # Rename the temp file to the old name
    file rename -force data_temp.tcl data.tcl
    

    On Tcl before 8.4 (if that's the case, you should upgrade if possible), you can use set data [lreplace $data 2 2 0] instead of lset data 2 0