2012-09-14 68 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