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?
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;