如何在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的内容?
答案 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);
}
}