I was using getopt_long read command line options. code:
#include <getopt.h>
#include <stdlib.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
int ch;
struct option longopts[] = {
{"password", required_argument, NULL, 'p'},
{"viewonly", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0}
};
while ((ch = getopt_long(argc, argv, "p:vh", longopts, NULL)) != -1) {
switch (ch) {
case 'p':
printf("optarg: %x %s\n", optarg, optarg);
break;
case 'v':
printf("viewonly is set\n");
break;
case 'h':
case '?':
default:
fprintf(stderr, "error\n");
exit(EXIT_FAILURE);
}
}
return 0;
}
and I using this command line option: ./a.out --password --viewonly
, It's supposed to print error message that --password
is missing argument, but getopt_long
never return '?', but treat --viewonly
as the optarg
of --password
. and the output is:
optarg: 24992bc4 --viewonly
I think it's strange, and what should I do to prevent getopt_long treat option name as argument?