Pergunta

I have the following code:

char opt;
int bla1,bla2,bla3;
char *myarg = NULL;
while((opt = getopt(argc,argv,"a:b:cd")) != -1)
{
    switch (opt)
    {
        case 'a':
            bla1 =  atoi(optarg);
            break;
        case 'b':
            myarg = optarg;
            break;
        case 'c':
            bla2 = 1;
            break;
        case 'd':
            bla3 = 1;
            break;
        default:
            break;
    }
}

I want to be able to use optarg for case 'b' but in case none is selected to get a default value. Right now requires arg and cannot bypass it and if I replace "b:" with "b" it ignores the argument.

How can I make it work in both situations?

Foi útil?

Solução

Some but not all versions of getopt allow you to indicate that an argument is optional by putting two colons after the relevant option character.

Wanting an optional argument to an option is a sign that your program is complicated enough that you should consider supporting long option names. Unfortunately there is no standard function to do this, but GNU libc has two: getopt_long and the even more powerful argp. If your software is GPL-compatible, you can get either of them from gnulib and then you don't depend on glibc.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top