Search code examples
c++getopt

getopt - capture '?'


I'm trying to use getopt in a C++ programme to parse command line arguments. The arguments are -d xxx, -s xxx and -?. I'm having trouble capturing the -? argument, which I want to print a standard usage message.

while ((c = getopt (argc, argv, "?d:s:")) != -1) {
    switch (c) {
        case 'd':
          ...do stuff
            break;
        case 's':
         ... do stuff
            break;
        case '?':
          // From example on GNU page, seems to capture -d, -s when no args provided.
          // Gets here when -d or -s provided, but no arguments for these options.
        default:
          // shut down
}

Try as I might, I can't seem to capture the '-?' option on its own. Is there a special trick to catch '?' on its own? Have I provided the correct pattern to getopt (ie. '?d:s:') At the moment, c is getting set to '?' whenever invalid options are provided, even if '?' is NOT provided on the command line.

Thanks guys.


Solution

  • getopt uses '?' as a special value to mean a missing option value or an unknown option. So I don't think there is any way to use getopt to handle '-?'.

    I would recommend '-h' for the help message. It's a common convention.