簡體   English   中英

如何從C中的stdout讀取

[英]how to read from stdout in C

我需要編寫一個 C 程序( myprogram )來檢查其他程序的輸出。 它應該基本上是這樣工作的:

./otherprogram | ./myprogram

但是我找不到如何從stdout (或管道)逐行讀取,然后將所有這些寫入stdout

一個程序的stdout成為下一個程序的stdin 只需從stdin讀取,你會沒事的。

shell 在運行myprogram時會為您連接一切。

順便說一句,這是負責的 bash 代碼: http : //git.savannah.gnu.org/cgit/bash.git/tree/execute_cmd.c

尋找execute_pipeline 不,代碼不容易理解,但它充分解釋了它。

使用以下命令創建可執行文件:

#include <stdio.h>

int main()
{
   char line[BUFSIZ];
   while ( fgets(line, BUFSIZ, stdin) != NULL )
   {
      // Do something with the line of text
   }
}

然后,您可以將任何程序的輸出通過管道傳輸給它,逐行讀取內容,對每一行文本進行處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM