tags:

views:

209

answers:

3

Hi,

getopt() is not behaving as I expect for short options.

eg: Invoking the below program with a missing parameter:

Valid Case: testopt -d dir -a action -b build

Error Case: testopt -d -a action -b build

This did not throw any error as I was expecting an error message operand missing for -d

Is this a known bug. If so is there any standard fix available.

#include <unistd.h>

/* testopt.c                       */
/* Test program for testing getopt */

int main(int argc, char **argv)
{
    int chr;
    while ( ( chr = getopt(argc, argv, ":d:a:b:") ) != -1 )
    {
            switch(chr)
            {
                    case 'a':
                            printf("Got a...\n");
                            break;
                    case 'b':
                            printf("Got b...\n");
                            break;
                    case 'd':
                            printf("Got d...\n");
                            break;
                    case ':':
                            printf("Missing operand for %c\n", optopt);
                            break;
                    case '?':
                            printf("Unknown option %c\n", optopt);
                            break;
            }
    }
    printf("execution over\n");
    return 0;
}

Appreciate the help in advance.

Thanks, Mathew Liju

A: 

According to the manual page, you should start your option string with a colon in order to make getopt() return ':' to indicate missing argument. The default seems to be returning '?'.

unwind
I modified with that option but it is behaving the same way.
Liju Mathew
+3  A: 

getopt() thinks -a is an argument for -d, not an option.

Try testopt -a action -b build -d - it should complain about missing argument.

You need to check for -d option (and all other options) that optarg has valid value - the one without dash in the beginning.

qrdl
The invocation is not under the control of the program and so I think verifying whether the first character is "-" is a solution as you said.
Liju Mathew
A: 

The above code works fine for me, using gcc 3.4.5 on Red Hat:

$ ./a.out -d test
Got d...
execution over

$ ./a.out -d
Missing operand for d
execution over

What's your environment?

UPDATE: OK, qrdl is spot on. How come getopt() works that way?

Bobby Jack