gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:09:22 26 4
gpt4 key购买 nike

我在 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

上面显示的代码行返回“?”在 c 中,但不是根据 getopt(3) 手册页预期的 ':':“错误和 -1 返回是 与 getopt() 相同”

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

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

最佳答案

我能看到的实现区分无效选项和缺少参数的有效选项的唯一方法是将选项结构的 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;
}

关于c - 如何确定缺少所需的选项参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40163234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com