如何确定缺少所需的选项参数?

How could one determine that required argument of option is missing?

我在 GNU/Linux 机器上使用 getopt_long。 将选项列表初始化为:

static struct option long_options[] = {
     {"mode", required_argument, 0, 9},
     {0, 0, 0, 0}
};

有下面一行代码

c = getopt_long(argc, argv, "", long_options, index_ptr);

当我 运行 我的程序使用命令时:

prog --mode

上面显示的代码行returns '?'在 c 中,但不是根据 getopt(3) 手册页预期的 ':':"Error 和 -1 returns 是 与 getopt()"

相同

是的,当 using/parsing 短选项时,可以在选项列表中写入类似“:m:”的内容,这样缺少参数的变量 c 将包含 ': ',不是'?',但是在解析 长选项时,应该如何区分两种情况(缺少参数,无效选项)?

如何区分无效选项和缺少必需参数的选项?

我能看到的实现区分无效选项和缺少参数的有效选项的唯一方法是将选项结构的 has_arg 字段设置为 optional_argument ,然后手动测试参数。那么 getopt_long() 只会 return 值 '?'当存在无效选项时,您可以通过查看 optarg 来检查指定选项是否具有参数。这是一个例子:

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

int main(int argc, char *argv[])
{
    int i, opt;
    int index = -1;

    static struct option long_options[] = {
        {"mode", optional_argument, NULL, 'm'},
        {0, 0, 0, 0}
    };

    /* suppress error messages */
    //opterr = 0;

    while ((opt = getopt_long(argc, argv, "", long_options, &index)) != -1) {
        if (opt == '?') {
            /* do something, perhaps: */
            //printf("Invalid option \n");
            //      exit(EXIT_FAILURE);
        }
        if (opt == 'm' && optarg == NULL) {
            printf("Missing argument in '--mode' option\n");
            exit(EXIT_FAILURE);
        }        
    }

    return 0;
}