Question

Is there way using getopt function to parse:

./prog -L -U

as same as:

./prog -LU    

This is my try (not working):

while ((c = getopt(argc, argv, "LU")) != -1) {
    switch (c) {
    case 'L':
        // L catch
        break;
    case 'U':
        // U catch
        break;
    default:
        return;
    }
}

In this simple example are only 2 parameters but in my project are required all combinations of 6 parameters. For example: -L or -LURGHX or -LU -RG -H etc. Can getopt() handle this? Or I must write complex parser to do that?

Was it helpful?

Solution

Save for a missing brace, your code works fine for me:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv) {
    int c;
    while ((c = getopt(argc, argv, "LU")) != -1) {
        switch (c) {
        case 'L':
            // L catch
            printf("L\n");
            break;
        case 'U':
            // U catch
            printf("U\n");
            break;
        default:
            break;
        }
    }
    return 0;
}
$ ./a.out -LU
L
U
$ ./a.out -L
L
$

OTHER TIPS

It behaves exactly as you would like:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char** argv) 
{
    int c;

    while ((c = getopt(argc, argv, "LU")) != -1) {
        switch (c) {
        case 'L':
            puts("'L' option");
            break;
        case 'U':
            // U catch
            puts("'U' option");
            break;
        default:
            puts("shouldn't get here");
            break;
        }
    }

    return 0;
}

And test it:

precor@burrbar:~$ gcc -o test test.c
precor@burrbar:~$ ./test -LU
'L' option
'U' option
precor@burrbar:~$ ./test -L -U
'L' option
'U' option

getopt() is a POSIX standard function that follows the POSIX "Utiltiy Syntax Guidelines", which includes the following:

Guideline 5: Options without option-arguments should be accepted when grouped behind one '-' delimiter.

getopt does seem capable of handling it, and it does

Here are some examples showing what this program prints with different combinations of arguments:

% testopt
aflag = 0, bflag = 0, cvalue = (null)

% testopt -a -b
aflag = 1, bflag = 1, cvalue = (null)

% testopt -ab
aflag = 1, bflag = 1, cvalue = (null)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top