【问题标题】:getopt() behaviour is unusualgetopt() 行为异常
【发布时间】:2008-11-05 09:10:26
【问题描述】:

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

【问题讨论】:

    标签: c getopt


    【解决方案1】:

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

    试试testopt -a action -b build -d - 它应该会抱怨缺少参数。

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

    【讨论】:

    • 调用不受程序控制,所以我认为验证第一个字符是否为“-”是您所说的解决方案。
    【解决方案2】:

    根据the manual page,您应该以冒号开始您的选项字符串,以使getopt() 返回':' 以指示缺少参数。默认似乎返回'?'

    【讨论】:

    • 我使用该选项进行了修改,但它的行为方式相同。
    【解决方案3】:

    上面的代码对我来说很好,在 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() 怎么会这样工作?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      • 2017-01-22
      • 2013-04-14
      • 2014-01-29
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多