简体   繁体   中英

Passing multiple arguments to C program

I've wrote a small C program, which takes 3 integers as arguments. If I am running it like this: myapp 1 2 3 runs fine, argc shows correctly 4, but if I do: echo 1 2 3 | myapp echo 1 2 3 | myapp , argc shows just 1.

The relevant part of the C code is:

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

What is wrong with this?

echo 1 2 3 | myapp echo 1 2 3 | myapp calls myapp with no arguments. Values are passed through stdin .

You may want to use this instead (if using bash in Unix):

    myapp `echo 1 2 3`

Or, if you have a list of numbers in a file called numbers.txt, you can do this as well:

    myapp `cat numbers.txt`

The pipe passes the output of the first process to the stdin of the second process, which has nothing to do with command-line arguments. What you want is xargs , which uses the output of the first process and uses it as command line arguments:

echo 1 2 3 | xargs myapp

echo 1 2 3 | myapp echo 1 2 3 | myapp will send 1 2 3 to the standard input of your program. If your program does not read from it, it will never see those numbers. You need to use for instance scanf for this to work. Note that you will have to parse the string by yourself to count the number of 'arguments' passed this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM