getopt()行为不寻常

getopt()行为不寻常

问题描述:

getopt()不像我期望的短期选项那样行事。getopt()行为不寻常

如:

有效案例:testopt -d dir -a action -b build

错误案例:testopt -d -a action -b build

,因为我在等一个错误信息操作缺少这并不会引发任何错误与遗漏的参数调用下面的程序for -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()认为-a-d的一个参数,而不是一个选项。

尝试testopt -a action -b build -d - 它应该抱怨失踪的论点。

您需要检查-d选项(和所有其他选项)optarg具有有效值 - 一开始没有破折号。

+0

调用不在程序的控制之下,因此我认为验证第一个字符是否为“ - ”是您所说的解决方案。 – 2008-11-05 10:22:31

the manual page,你应该开始你的选项字符串以冒号为了使getopt()回报':'指示缺少的参数。默认情况下,似乎返回'?'

+0

我使用该选项进行了修改,但其行为方式相同。 – 2008-11-05 09:20:27

上面的代码正常工作对我来说,使用gcc 3.4.5在Red Hat:

$ ./a.out -d test 
Got d... 
execution over 

$ ./a.out -d 
Missing operand for d 
execution over 

什么是你的环境?

UPDATE:好的,qrdl是现货。 getopt()如何以这种方式工作?