different order of command line options in a command affecting my output

109 views Asked by At

i am making a program in c that accepts command line arguments like --version , --download.

when i do this :

$program --version --download file

the program outputs the version and downloads the file. But when i do this:

$program --download --version file

the program considers --version to be the argument to --download.

I have used getopt_long() function for parsing the command line arguments. Here's a snippet from my code:

while ((ch = getopt_long(argc, argv, "d:g:hv", longoptions, &optindex)) != -1 )
{
    switch(ch)
    {
            case 'd' :
                if ( optarg )
                    printf("Downloading %s...\n" , optarg);
                iso(optarg);
                break ;

            case 'g' :
                if ( optarg )
                    printf("Downloading glug-mirror automation script for %s ...\n", optarg);
                getscript(optarg);
                break ; 

            case 'v' : 
                printf("glug version 1.0.0 ( NIT Hamirpur)\n");
                break ;

            case 'h' :
                usage(status);
                break ;

            default :
                status  = 2 ; 
               usage(status);
    }
}
1

There are 1 answers

2
TheCodeArtist On

getoptlong() is doing exactly what it is supposed to do.

  • The format-string "d:g:hv" implies that the parameters d and g require a value.
  • Anything specified following a command-line parameter is consider a value being passed to it.

You should run your program as

$program --download file --version

Checkout this detailed example demonstrating the various aspects of using getoptlong().


How rm can handle the differing position of its cmd-line params?

Apparently because rm's parameters (r, v etc.) do NOT accept any values as arguments. Thus directory does not get passed to any of them but rather is a separate cmd-line argument on its own. You can confirm this from the source-code of rm.

To do something similar for your program, you will need to modify the optstring to "dghv" and handle the parameter "file" separately.