Frantique
Frantique

Reputation: 175

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, 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?

Upvotes: 0

Views: 2631

Answers (3)

M Oehm
M Oehm

Reputation: 29136

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

Upvotes: 3

damienfrancois
damienfrancois

Reputation: 59340

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.

Upvotes: 0

mcleod_ideafix
mcleod_ideafix

Reputation: 11448

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`

Upvotes: 4

Related Questions