我从正在编写的程序中解析参数时遇到问题,代码如下:
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:
printf("Help will be printed very soon -:)\n");
}
}
}
当我运行我的程序时,我得到了一些奇怪的输出:
./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!!!