【发布时间】:2017-03-28 09:54:29
【问题描述】:
我正在尝试使用 getopt_long() 创建一个带有可选参数的选项。
这是我的代码:
static struct option long_options[] = {
{"help", no_argument, NULL, 'h'},
{"debug", no_argument, NULL, 'd'},
{"config", optional_argument, NULL, 'c'},
{NULL, 0, NULL, 0}
};
while ((ch = getopt_long(argc, argv, "hdc::", long_options, NULL)) != -1) {
// check to see if a single character or long option came through
switch (ch) {
case 'h':
opt.help = true;
break;
case 'd':
opt.debug = true;
break;
case 'c':
printf("C-Option: %s\n", optarg);
if (optarg != NULL) {
opt.configFile = optarg;
}
break;
}
}
我正在尝试将 -c 的参数设为可选,以便您可以使用以下选项运行程序:
-c test.cfg --> optarg = "test.cfg"
-c --> optarg = null
如果我设置c:: 而不是optarg 总是null。
如果我设置了c:,我会得到一个错误:option requires an argument -- 'c'
我做错了什么?我可以设置其他选项吗?
【问题讨论】:
-
@DavidBowling 不适合我
-
@DavidBowling 那太好了
-
为什么不定义两个选项:
--opt-1_with-arg和-opt-1_use-default?或更短:--o1a和--o1d或更短:--o和--od;-)