• We should now be fully online following an overnight outage. Apologies for any inconvenience, we do not expect there to be any further issues.

piping to C

toughwimp11

Senior member
May 8, 2005
415
0
76
I'm trying to make a program in c that will print the output from another program, along with some other stuff but I'm having trouble doing this

Basically, let's say I have a file test.txt which contains the text "hi"
and I have a program "abcd"

$cat test.txt | ./abcd
hi
$./abcd < test.txt
hi

More importantly, what I want is to store what was piped or sent to the C program in a string, which I can then do anything with (such as print it to stdout)

I cant seem to make this work. some of the things i've tried give me write error: Broken pipe

any suggestions on what the c syntax is?
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
1 #include <stdio.h>
2
3 int main() {
4 char buff[1024];
5 while(fgets(buff,1024,stdin)) {
6 printf("I read [%s]\n",buff);
7 }
8 return 0;
9 }

hms-daring(6)% echo "foo" | ./a.out
I read [foo
]
 

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,698
4,660
75
"Broken pipe" indicates that you're closing stdin in the C code before the other program has finished writing to it.

Edit: Nevermind.