【发布时间】:2011-11-21 09:23:36
【问题描述】:
我在从我正在编写的程序中解析参数时遇到问题,代码如下:
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!!!
【问题讨论】:
-
为什么奇怪?你期待什么?
-
最后三个执行输出奇怪!!!
-
不,不是。你传递了
-p,它会将下一件事(o或or)解释为计数,并忽略80。p应该在o和r之后。在第四次运行中,它只计算每个字母一次。 -
哦。它接受折叠在一起的单字母选项,就像在 Unix 中键入
ls -ltr时一样。你不知道吗?退出!!!,这不像你是这里任何人的老板。 -
至于 getopt(),它可以工作,但它的行为不像您认为的那样。欢迎来到您余下的编码生涯。如果你想改变它,你将不得不自己做。或者你将不得不接受一种不同的解析输入的方式。而且无论如何,您都必须验证您的输入。相信我。
标签: c command-line-arguments getopt-long