向C程序传递多个参数

向C程序传递多个参数,c,command-line,C,Command Line,我写了一个小C程序,它以3个整数作为参数。如果我这样运行:myapp 1 2 3运行良好,argc正确显示4,但如果我这样运行:echo 1 2 3 | myapp,argc仅显示1 C代码的相关部分为: #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char **argv) { printf("Entered: %i\n", argc); if (

我写了一个小C程序,它以3个整数作为参数。如果我这样运行:myapp 1 2 3运行良好,argc正确显示4,但如果我这样运行:echo 1 2 3 | myapp,argc仅显示1

C代码的相关部分为:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv)
{
printf("Entered: %i\n", argc);
if ( argc < 4)
{
printf("You must enter 3 integers as command line arguments!\n");
exit(1);
}
}
这有什么问题?

echo 1 2 3 | myapp调用myapp时没有参数。值通过stdin传递

如果在Unix中使用bash,则可能需要使用此选项:

    myapp `echo 1 2 3`
或者,如果在名为numbers.txt的文件中有一个数字列表,您也可以这样做:

    myapp `cat numbers.txt`

echo 1 2 3 | myapp将向程序的标准输入发送1 2 3。如果您的程序不从中读取,它将永远看不到这些数字。例如,您需要使用此工具才能正常工作。请注意,您必须自己分析字符串以计算以这种方式传递的“参数”的数量。

管道将第一个进程的输出传递给第二个进程的stdin,这与命令行参数无关。您需要的是xargs,它使用第一个进程的输出并将其用作命令行参数:

echo 1 2 3 | xargs myapp

是的,我累了,我忘记了沙尔格。。。谢谢我会尽快接受你的答复。