C getopt()行为是不寻常的
C getopt()行为是不寻常的,c,getopt,C,Getopt,getopt() 例如:调用缺少参数的以下程序: 有效案例:testopt-d dir-a action-b build 错误案例:testopt-d-a操作-b构建 这没有引发任何错误,因为我希望-d 这是已知的bug吗 如果是,是否有任何标准的修复程序可用 我的代码: #include <unistd.h> /* testopt.c */ /* Test program for testing getopt */ int main(
getopt()
例如:调用缺少参数的以下程序:
有效案例:testopt-d dir-a action-b build
错误案例:testopt-d-a操作-b构建
这没有引发任何错误,因为我希望-d
- 这是已知的bug吗李>
- 如果是,是否有任何标准的修复程序可用
我的代码:
#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;
}
#包括
/*testopt.c*/
/*测试getopt的测试程序*/
int main(int argc,字符**argv)
{
int-chr;
while((chr=getopt(argc,argv,”:d:a:b:)!=-1)
{
开关(chr)
{
案例“a”:
printf(“得到一个…”);
打破
案例“b”:
printf(“gotb...n”);
打破
案例“d”:
printf(“获得d…);
打破
案例“:”:
printf(“缺少%c\n的操作数”,optpt);
打破
案例“?”:
printf(“未知选项%c\n”,optopt);
打破
}
}
printf(“执行结束”);
返回0;
}
根据,您应该以冒号开头选项字符串,以便使getopt()
返回':'
以指示缺少的参数。默认值似乎是返回'?'
getopt()
认为-a
是-d
的参数,而不是选项
尝试testopt-a action-b build-d
——它应该会抱怨缺少参数
您需要检查-d
选项(以及所有其他选项),optarg
具有有效值,即开头没有破折号的值。以上代码对我来说很好,使用红帽上的gcc 3.4.5:
$ ./a.out -d test
Got d...
execution over
$ ./a.out -d
Missing operand for d
execution over
你的环境是什么
更新:好的,qrdl已就位。为什么getopt()是这样工作的?我使用该选项进行了修改,但其行为方式相同。调用不受程序控制,因此我认为验证第一个字符是否为“-”是一个解决方案,正如您所说。