how to read from stdout in C

若如初见. 提交于 2021-02-18 12:45:09

问题


I need to write a C program (myprogram) which checks output of other programs. It should basically work like this:

./otherprogram | ./myprogram

But I could not find how to read line-by-line from stdout (or the pipe), and then write all this to stdout.


回答1:


Create an executable using:

#include <stdio.h>

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

Then you can pipe the output of any program to it, read the contents line by line, do something with each line of text.




回答2:


One program's stdout becomes the next program's stdin. Just read from stdin and you will be fine.

The shell, when it runs myprogram, will connect everything for you.

BTW, here is the bash code responsible: http://git.savannah.gnu.org/cgit/bash.git/tree/execute_cmd.c

Look for execute_pipeline. No, the code is not easy to follow, but it fully explains it.



来源:https://stackoverflow.com/questions/24214038/how-to-read-from-stdout-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!