getopt_long problem
i have a problem with parsing arguments from a program that i'm writing, the code is below:
void parse_args(int argc, char** argv)
{
char ch;
int index = 0;
struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "port", required_argument, NULL, 'p' },
{ "stop", no_argument, NULL, 's' },
{ 0, 0, 0, 0 }
};
while ((ch = getopt_long(argc, argv, "hp:s", options, &index)) != -1) {
switch (ch) {
case 'h':
printf("Option h, or --help.\n");
break;
case 's':
printf("Option s, or --stop.\n");
break;
case 'p':
printf("Option p, or --port.\n");
if (optarg != NULL)
printf("the port is %s\n", optarg);
break;
case '?':
printf("I don't understand this option!!!\n");
case -1:
break;
default:
开发者_如何学C printf("Help will be printed very soon -:)\n");
}
}
}
When i run my program i got some strange output :
./Server -p 80
Option p, or --port.
the port is 80
./Server -po 80
Option p, or --port.
the port is o
./Server -por 80
Option p, or --port.
the port is or
./Server -hoho
Option h, or --help.
Server: invalid option -- o
I don't understand this option!!!
I think the confusion stems from a misunderstanding of long get opt. Essentially it will do partial string match only when you use the --
form. When you only use -
it will fallback to standard parsing so -por 80
is matched as -p or 80
(as in, the option is -p
and the argument is or
). Try the same thing with --po
and --por
. As for help, try --he
or--hel
精彩评论