Reputation: 467
I want to enter some command line arguments at run time. Like
./program abc def ghi
argc
would be 4 in this case. No problem in this. But if I do
./program abc def *
or even
./program * abc def
the variable argc
gives me a value far larger than 4.
On printing the entire argv
array (leaving aside the 0th argument; ./program
) as strings, I am given a list where the first two elements are abc
and def
and the others are all file names of the files contained in the working directory.
I am trying to learn C from K&R. I was trying to make an RPN calculator where we can give expressions like ./program 2 4 *
.
What is the reason for this? Or am I wrong somewhere?
Upvotes: 3
Views: 484
Reputation: 14649
If you're using bash, start the shell with the -f
switch to turn off expansion of things like *
bash -f
Upvotes: 2
Reputation: 3203
You can prevent * from expanding into file names by putting it into single quotes, i.e.
./program 2 4 '*'
This way your program will receive 3 input arguments with values "2", "4" and "*" in terms of C strings.
Upvotes: 0
Reputation: 47553
Shells have a feature called globbing, where they expand certain patterns, such as *
to the matching files. If in the current directory you have the following:
file1 file2 somethingelse dir1
then calling:
any_program *
will be equivalent to:
any_program file1 file2 somethingelse dir1
Or if you do:
any_program fi*
it will be equivalent to:
any_program file1 file2
This is a feature of the shell. Your C program is well-behaved.
Since shells are different, let's assume you are using bash
. To prevent bash
from performing expansions, you should quote the argument. For example:
any_program "fi*"
will actually pass fi*
to your program, without expanding it to file1 file2
.
Upvotes: 10
Reputation: 2320
The commandline interpretter processes the *
character as a wildcard before passing the arguments to your program, just the same as it does if you type DIR *
.
The simple solution is to devise a meaningful parameter that does not get interpretted.
Upvotes: 3