Search code examples
cshellosx-mavericksargc

argc giving erroneous value in C program


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?


Solution

  • 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.