bash + c管道参数

时间:2016-11-06 20:29:55

标签: c bash parameters pipe

如何在c代码中访问管道参数?

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

击:

cat file.txt | ./test

它只打印第一个参数argv[0] = ./test。如何在c代码(作为参数)中访问file.txt的内容?

1 个答案:

答案 0 :(得分:0)

使用管道,您的程序在其标准输入中获取file.txt的内容。所以,请阅读stdin。例如,您可以使用fgets()逐行阅读:

#include <stdio.h>

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

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