c - bash + c 管道参数

标签 c bash parameters pipe

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

测试.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

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

最佳答案

通过管道,您的程序可以在其标准输入中获取 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);
   }
}

关于c - bash + c 管道参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40454182/

相关文章:

java - 如果向前输入,如何在 URL 中附加查询参数?

c - 如何在 Main() 之前创建数组/结构并在 C 中对其进行初始化

bash - 如何使用 awk 或 bash 将输出保存到文件夹?

c - 传递参数 1 从指针生成整数而没有强制转换警告

ruby - 是否可以从 ruby​​ 脚本返回值并在 c 或 shell 脚本中读取该值?

linux - 安装时提示是或否的 Shell 脚本

斯卡拉 2.9 : plans for type inference of function parameters with default arguments?

c# - 无法理解方法参数

c - 为什么我们不能用C语言中的 "%d"来代替指针的 "%u"呢?

c - 如何使用函数中生成的两个随机数作为矩阵坐标?