dontHaveName dontHaveName - 1 month ago 23
C Question

bash + c pipe parameter

How can I access piped parameter in c code?

test.c

int main( int argc, char *argv[] ) {
int i = 0;
for (i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
}


Bash:

cat file.txt | ./test


It prints just first argument
argv[0] = ./test
. How can I access content of file.txt inside c code (as parameter)?

usr usr
Answer

With the pipe, your program gets the content of file.txt in its stdin. So, read from stdin. For example you can use fgets() to read line by line:

#include <stdio.h>

int main(int argc, char *argv[]) {
   int i = 0;

   char line[1024];
   while(fgets(line, sizeof line, stdin)) {
     printf("%s", line);
   }
}