【问题标题】:File Read and Write in tcltcl 中的文件读写
【发布时间】:2012-11-08 19:11:20
【问题描述】:

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

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”为空{“”}。我想我在阅读文件时遇到了麻烦。请帮我解决这个问题

【问题讨论】:

    标签: tcl


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-13
      相关资源
      最近更新 更多