Reputation: 749
I saw some previous posts related to opening a file to perform read and write operations but I din't get an answer for my task. I want to append some results to a file (should create a new file if it does not exist).
However, if the file already has result then append should be skipped and move on to next search for next result. I wrote a script for this and I have problem in reading the file.
The script is something like this:
proc example {} {
set a [result1 result2 ... result n]
set op [open "sample_file" "a+"]
set file_content ""
while { ![eof $op] } {
gets $op line
lappend file_content $line
}
foreach result $a {
if {[lsearch $file_content $result] == -1} {
puts $op $result
}
}
close $op
}
Note: In this script I find variable "line" to be empty {""}. I guess I have trouble in reading the file. Please help me with this
Upvotes: 1
Views: 8140
Reputation: 40773
What you forgot, is to seek to the beginning of the file before reading:
proc example {} {
set a {result1 result2 ... result n}; # <== curly braces, not square
set op [open "sample_file" "a+"]
set file_content ""
seek $op 0; # <== need to do this because of a+ mode
while { ![eof $op] } {
gets $op line
lappend file_content $line
}
foreach result $a {
if {[lsearch $file_content $result] == -1} {
puts $op $result
}
}
close $op
}
You can simplify the reading (while loop and all), with one single read statement:
proc example {} {
set a {result1 result2 result3}
set op [open "sample_file" "a+"]
seek $op 0
set file_content [read $op]
foreach result $a {
if {[lsearch $file_content $result] == -1} {
puts $op $result
}
}
close $op
}
example
Upvotes: 8