文件读写tcl

我看到一些以前的帖子与打开文件来执行读写操作有关,但我不能为我的任务得到答案。 我想追加一些结果到一个文件(如果它不存在,应该创建一个新文件)。
但是,如果文件已经有结果,那么应该跳过追加并继续下一个搜索结果。 我为此写了一个脚本,在阅读文件时遇到问题。 脚本是这样的:

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
}

注意:在这个脚本中我发现变量“line”是空的{“”}。 我想我在阅读文件时遇到了麻烦。 请在这件事上给予我帮助


你忘了,是在阅读之前寻找文件的开头:

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
}

更新

您可以使用单个读取语句简化读取(while循环和全部):

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
链接地址: http://www.djcxy.com/p/67737.html

上一篇: File Read and Write in tcl

下一篇: keylset bug in Tcl 8.4 and 8.5?