Search code examples
unixgccposixlibcgetopt

How to prevent getopt from being confused with option with missing argument?


Say, I have code:

while ((c = getopt(argc, argv, ":n:p")) != -1) {
    switch (c) {
    case 'n':
        syslog(LOG_NOTICE, "n: %s", optarg);
        break;
    case 'p':
        /* ... some code ... */
        break;
    case ':':
        /* handle missing arguments to options requiring arguments */
        break;
    /* some cases like '?', ... */
    default:
        abort();
    }
}

When I call my program as

./main -n -p

it prints:

n: -p

Why does not getopt return : to indicate that argument to -n is missing but instead uses -p as parameter argument?


Solution

  • It is perfectly OK to have an option argument that starts with a dash and generally resembles another option. There is no reason for getopt to report an error.

    If a program doesn't want to accept such option arguments, it should specifically check for them, e.g.

       if (optarg[0] == '-') {
          // oops, looks like user forgot an argument
          err("Option requires an argument");
       }