dontHaveName dontHaveName - 5 months ago 63
C Question

bash + c pipe parameter

How can I access piped parameter in c code?


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


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

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);