user3155036
user3155036

Reputation: 167

how to read from stdout in C

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.

Upvotes: 5

Views: 11350

Answers (2)

R Sahu
R Sahu

Reputation: 206577

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.

Upvotes: 5

Sean Perry
Sean Perry

Reputation: 3886

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.

Upvotes: 7

Related Questions