2012-09-14 63 views
2

这是关于在tcl中读取文件的问题。 我打开一个缓冲流写入,我只有一个文件处理程序引用它 现在,当逐行读取这个缓冲区,在某些情况下,我必须把缓冲区的所有内容,请建议我怎么能实现这一点。 所以我只是粘贴一个示例代码来解释我的要求。在tcl中读取缓冲流

catch { open "| grep" r } pipe 
while { [gets $pipe line] } { 
     if { some_condition } { 
      ## display all the content of $pipe as string 
     } 
} 

感谢 鲁奇

回答

4

从管道读直到它被另一端关闭,只是使用read $pipe。这然后让你这样做:如果你想从前面的管道输出任何东西

set pipe [open "| grep" r] 
while { [gets $pipe line] >= 0 } { # zero is an empty line... 
    if { some_condition } { 
     puts [read $pipe] 
     ### Or, to include the current line: 
     # puts $line\n[read $pipe] 
    } 
} 

,则必须将其保存在一个变量。

+0

我还建议不要在问题中围绕'open | ...'放置'catch',因为您可以获取的错误消息永远不会是有效的通道名称。 –

+0

另外应该注意的是,GNU'grep'默认使用完全缓冲,所以如果它真的打算读取它的行输出,建议将'--line-buffered'命令行选项传递给它。不确定其他的'grep'实现。 – kostix