3

I have a program use getopt_get() to parse command line arguments. My code is like this :

int opt;
int optionIndex;
static struct option longOptions[] = {
    {"help", no_argument, NULL, 'h'},
    {"test", no_argument, NULL, 't'},
    {0, 0, 0, 0}
}; 
while ((opt = getopt_long(argc, argv, "ht", longOptions, &optionIndex)) != -1) {
    switch (opt) {
        case 'h':
            help();
            return 0;
            break;
        case 't':
            init();
            test();
            return 0;
            break;
        case '?':
            help();
            return 1;
            break;
        default:
            printf("default.\n");
    }   

When I pass correct command line arguments to program, it works wells. But when wrong arguments are passed to program, it will print annoying and superfluous words like this.

For example, i pass wrong argument 'q' to program

$ ./program -q
./program: invalid option -- 'q'
Usage: -h -t

When there are wrong arguments, I just want it run my function help() without printing any word.

./program: invalid option -- 'q'

How can I stop getopt_long to print this annoying word and just print nothing?

kuro
  • 3,214
  • 3
  • 15
  • 31
Edure
  • 73
  • 2
  • 8

1 Answers1

8

Read the fine manual...

If getopt() does not recognize an option character, it prints an error message to stderr, stores the character in optopt, and returns '?'. The calling program may prevent the error message by setting opterr to 0.

So, try this before calling getopt_long:

opterr = 0;
rustyx
  • 80,671
  • 25
  • 200
  • 267
  • 1
    `opterr` is POSIX: http://pubs.opengroup.org/onlinepubs/9699919799/functions/getopt.html, so even though `getopt_long()` isn't POSIX, it's likely to work. – Andrew Henle Jun 08 '17 at 12:29
  • Thanks, It work! And `opterr = 0;` should written before optget_long() as a flag. – Edure Jun 08 '17 at 12:42
  • A better online manpage link: http://man7.org/linux/man-pages/man3/getopt.3.html . The bad editing in the old version clouds the fact that you can also suppress error messages by putting a colon at the front of the option string. – rici Jun 08 '17 at 15:26