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

时间:2016-10-20 19:46:27

标签: c linux getopt-long command-line-parsing

I use getopt_long on GNU/Linux machine. Initialize options list as:

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

Have following line of code

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

When I run my program with command:

prog --mode

Above shown line of code returns '?' in c, but not ':' as expected according to getopt(3) man page: "Error and -1 returns are the same as for getopt()"

Yes, when using/parsing short options one could write in options list something like ":m:", so that variable c on missing argument would contain ':', not '?', but what one should do to distinguish between two cases(missing argument, invalid option) when parsing only long options?

How could one distinguish between invalid option and option with missing required argument?

1 个答案:

答案 0 :(得分:2)

我可以看到实现区分无效选项和缺少参数的有效选项的目标的唯一方法是将选项结构的has_arg字段设置为optional_argument,并且然后手动测试参数。然后getopt_long()只会返回'?'当存在无效选项时,您可以通过查看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;
}