Question

My code uses getopt to take the arguments from the command-line. I want to be able to take three required arguments, and an optional fourth argument. Let's call these input A and B respectively: ./main string1 string2 filename or ./main -n 3 string1 string2 filename.

I'm told that the optional argument need not be placed at the beginning, so the following should also work. Let's call this input C: ./main string1 string2 -n 3 filename. Please note that the other 3 arguments do have to be in that order. This is the part that I'm having trouble with.

Currently, my code looks like this:

int c;
int n;
while ((c = getopt(argc,argv,"n:"))!=-1) {
    printf("Loop\n");
    switch (c) {
            case 'n':
                cvalue = optarg;
                n = atoi(optarg);
                break;
            case '?':
                break;
            default:
                break;
    }
}

If I do input B, the code works, i.e goes in the loop and the input gets correctly assigned to n. However, if I do input C, it does not even go in the loop i.e it seems to not even be registering the -n 3 in the arguments. Is this the expected behavior, or am I missing something in my code? How can I fix the problem?

Was it helpful?

Solution

getopt() implements the "standard" command line structure, i.e. all options come before all arguments (ref). Not all Unix commands adhere to this "standard"; if your command needs to deviate, you can parse argv[] by hand, without the getopt() function. From man 3 getopt:

If there are no more option  characters,  getopt()  returns  -1.   Then
optind  is  the  index in argv of the first argv-element that is not an
option.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top