0

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?

3 Answers 3

4

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`
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

Yep, I am tired, I've forgot the xargs... Thanks! :) I will accept you r answer asap.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.