简体   繁体   中英

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.

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 puts ing 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM