2

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;
}
4

3 回答 3

4

getopt()thinks-a是 的参数-d,而不是选项。

尝试testopt -a action -b build -d- 它应该抱怨缺少论点。

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

于 2008-11-05T09:35:28.127 回答
0

根据手册页,您应该以冒号开头选项字符串,以便getopt()返回':'以指示缺少参数。默认似乎正在返回'?'

于 2008-11-05T09:16:20.023 回答
0

上面的代码对我来说很好,在 Red Hat 上使用 gcc 3.4.5:

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

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

你的环境是什么?

更新:好的,qrdl 是正确的。getopt() 怎么会这样工作?

于 2008-11-05T10:26:38.460 回答