【问题标题】:C - getopt incorrectly interprets next option as argument for previous optionC - getopt 错误地将下一个选项解释为上一个选项的参数
【发布时间】:2021-08-03 15:18:43
【问题描述】:

我正在通过以下方式使用getopt

     while ((c = getopt(argc, argv, ":a:b")) != -1) {
        switch (c) {
        case 'a':
          printf("option: a argument: %s\n", optarg);
          break; 
        case 'b':
          printf("option: b\n");
          break;
        case ':':
          if(optopt == 'a') {
            printf("option: a argument: default\n");
          else {
            fprintf(stderr, "argument required!\n");
          }
    }

这个想法是让选项a 接受一个可选参数,如果没有提供则使用默认值。

但是,如果我这样运行我的程序: ./main -a -b,最终打印出来的是:

option a: argument -b

我想要的是:

option: a argument: default
option: b

我怎样才能让getopt 意识到-a 后面的内容实际上是另一种选择,而不是它的论点?

【问题讨论】:

    标签: c getopt


    【解决方案1】:

    getopt 错误地将下一个选项解释为上一个选项的参数

    不,getopt 正确地将下一个参数解释为参数。

    我怎样才能让 getopt 意识到 -a 后面的内容实际上是另一个选项而不是它的论点?

    你不能 - getopt 不支持可选参数。您可以:接受限制、推出自己的选项解析方法或使用不同的实用程序进行选项解析。

    【讨论】:

      【解决方案2】:

      来自 MAN 页面:

      optstring is a string containing the legitimate option characters.   If
         such  a  character is followed by a colon, the option requires an argument, so getopt() places a pointer to the following text  in  the  same
         argv-element,  or  the  text  of the following argv-element, in optarg.
         Two colons mean an option takes an optional arg;
      

      因此,":a:b" 最好写成:`"a::b",它允许 '-a' 有一个可选参数,而 'b' 没有参数。

      阅读getopthow to use getopt的详细信息

      【讨论】:

      • Two colons mean an option takes an optional arg; .... This is a GNU extension.
      猜你喜欢
      • 1970-01-01
      • 2012-08-05
      • 1970-01-01
      • 2020-08-12
      • 2021-03-19
      • 2023-03-21
      • 1970-01-01
      • 2012-09-19
      • 2013-03-06
      相关资源
      最近更新 更多