我正在学习使用getopt_long
。从维基百科示例 2(使用GNU扩展getopt_long)中,我看到了以下代码:
#include <stdio.h> /* for printf */
#include <stdlib.h> /* for exit */
#include <getopt.h> /* for getopt_long; POSIX standard getopt is in unistd.h */
int main (int argc, char **argv) {
int c;
int digit_optind = 0;
int aopt = 0, bopt = 0;
char *copt = 0, *dopt = 0;
static struct option long_options[] = {
{"add", 1, 0, 0},
{"append", 0, 0, 0},
{"delete", 1, 0, 0},
{"verbose", 0, 0, 0},
{"create", 1, 0, 'c'},
{"file", 1, 0, 0},
{NULL, 0, NULL, 0}
};
int option_index = 0;
while ((c = getopt_long(argc, argv, "abc:d:012",
long_options, &option_index)) != -1) {
int this_option_optind = optind ? optind : 1;
switch (c) {
case 0:
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;
case '0':
case '1':
case '2':
if (digit_optind != 0 && digit_optind != this_option_optind)
printf ("digits occur in two different argv-elements.\n");
digit_optind = this_option_optind;
printf ("option %c\n", c);
break;
case 'a':
printf ("option a\n");
aopt = 1;
break;
case 'b':
printf ("option b\n");
bopt = 1;
break;
case 'c':
printf ("option c with value '%s'\n", optarg);
copt = optarg;
break;
case 'd':
printf ("option d with value '%s'\n", optarg);
dopt = optarg;
break;
case '?':
break;
default:
printf ("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind < argc) {
printf ("non-option ARGV-elements: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
printf ("\n");
}
exit (0);
}
我不太理解
option long_options[]
对象。
第一列
我认为long_options[]
的第一列应该是用户在命令行中使用的长标志(即跟在--
后面的内容)。
第二列
我原本认为第二列应该只包含no_argument
,required_argument
或optional_argument
,但实际上我看到的是0和1。
第三列
我不理解第三列的含义。
第四列和最大标志数
第四列是用于switch语句的唯一标识符。然而,如果唯一标识符只能是一个字符,那么我们是否限制于所有小写字母(26个)+所有大写字母(26个)+数字(10个)+可能一些特殊字符,总共不超过62个不同的参数?这是getopt
的限制吗?如果我理解有误,请问如何在第三个参数中指定超过两个字符以标识标志(例如""abc:d:012""
)?我想
option long_options[]
的最后一行是用于当getopt
返回-1
时,因此实际上并不重要,只要它存在即可。
C
。那是个错误,我本意是使用C++
。(标签已更正)。谢谢。 - Remi.bgetopt_long()
的哪个部分在引起问题? - Jonathan Lefflerstruct option
成员的含义。请参考真正的getopt_long()
文档,可以在许多地方找到,显然不包括维基百科。例如,在这里,或者 这里,更不用说通过man
命令在您自己的计算机上查找了。 - John Bollinger