getopt() 行为异常
getopt()
对于短选项的行为并不符合我的预期。
例如:调用缺少参数的以下程序:
有效案例:testopt -d dir -a action -b build
错误案例:testopt -d -a action -b build
这没有引发任何错误,因为我期待 -d
缺少错误消息操作数
- 这是一个已知的错误吗?
- 如果是这样,是否有任何标准修复可用?
我的代码:
#include <unistd.h>
/* testopt.c */
/* Test program for testing getopt */
int main(int argc, char **argv)
{
int chr;
while ( ( chr = getopt(argc, argv, ":d:a:b:") ) != -1 )
{
switch(chr)
{
case 'a':
printf("Got a...\n");
break;
case 'b':
printf("Got b...\n");
break;
case 'd':
printf("Got d...\n");
break;
case ':':
printf("Missing operand for %c\n", optopt);
break;
case '?':
printf("Unknown option %c\n", optopt);
break;
}
}
printf("execution over\n");
return 0;
}
getopt()
is not behaving as I expect for short options.
eg: Invoking the below program with a missing parameter:
Valid Case: testopt -d dir -a action -b build
Error Case: testopt -d -a action -b build
This did not throw any error as I was expecting an error message operand missing for -d
- Is this a known bug?
- If so, is there any standard fix available?
My code:
#include <unistd.h>
/* testopt.c */
/* Test program for testing getopt */
int main(int argc, char **argv)
{
int chr;
while ( ( chr = getopt(argc, argv, ":d:a:b:") ) != -1 )
{
switch(chr)
{
case 'a':
printf("Got a...\n");
break;
case 'b':
printf("Got b...\n");
break;
case 'd':
printf("Got d...\n");
break;
case ':':
printf("Missing operand for %c\n", optopt);
break;
case '?':
printf("Unknown option %c\n", optopt);
break;
}
}
printf("execution over\n");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
getopt()
认为-a
是-d
的参数,而不是选项。尝试 testopt -a action -b build -d - 它应该抱怨缺少参数。
您需要检查
-d
选项(以及所有其他选项)是否optarg
具有有效值 - 开头没有破折号的值。getopt()
thinks-a
is an argument for-d
, not an option.Try
testopt -a action -b build -d
- it should complain about missing argument.You need to check for
-d
option (and all other options) thatoptarg
has valid value - the one without dash in the beginning.根据 手册页,您应该以冒号开头选项字符串,以使
getopt()
返回':'
来指示缺少的参数。 默认值似乎是返回'?'
。According to the manual page, you should start your option string with a colon in order to make
getopt()
return':'
to indicate missing argument. The default seems to be returning'?'
.上面的代码对我来说工作得很好,在 Red Hat 上使用 gcc 3.4.5:
你的环境是什么?
更新:好的,qrdl 是正确的。 getopt() 为什么会这样工作?
The above code works fine for me, using gcc 3.4.5 on Red Hat:
What's your environment?
UPDATE: OK, qrdl is spot on. How come getopt() works that way?