下面看一下
getopt_long
和
getopt_long_only
(参考
getopt(3) – Linux man page):
#include <getopt.h>
int getopt_long(int argc, char * const argv[],
const char *optstring,
const struct option *longopts, int *longindex);
int getopt_long_only(int argc, char * const argv[],
const char *optstring,
const struct option *longopts, int *longindex);
getopt_long
除了可以处理short option
外,还可以处理long option
(以--
开头)。关于struct option
定义如下:
struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
The meanings of the different fields are:
name
is the name of the long option.
has_arg
is: no_argument (or 0) if the option does not take an argument; required_argument (or 1) if the option requires an argument; or optional_argument (or 2) if the option takes an optional argument.
flag
specifies how results are returned for a long option. If flag is NULL, then getopt_long() returns val. (For example, the calling program may set val to the equivalent short option character.) Otherwise, getopt_long() returns 0, and flag points to a variable which is set to val if the option is found, but left unchanged if the option is not found.
val
is the value to return, or to load into the variable pointed to by flag.
如果flag
是NULL
,getopt_long
会返回val
的值,因此通常会把flag
置成NULL
,把val
置成与long option
对应的short option
。否则getopt_long
会返回0
,并把val
的值赋给flag
。
参考下列代码(选自GNU binutils
中的size
命令)可以更好地了解getopt_long
:
#define OPTION_FORMAT (200)
#define OPTION_RADIX (OPTION_FORMAT + 1)
#define OPTION_TARGET (OPTION_RADIX + 1)
static struct option long_options[] =
{
{"common", no_argument, &show_common, 1},
{"format", required_argument, 0, OPTION_FORMAT},
{"radix", required_argument, 0, OPTION_RADIX},
{"target", required_argument, 0, OPTION_TARGET},
{"totals", no_argument, &show_totals, 1},
{"version", no_argument, &show_version, 1},
{"help", no_argument, &show_help, 1},
{0, no_argument, 0, 0}
};
while ((c = getopt_long (argc, argv, "ABHhVvdfotx", long_options,
(int *) 0)) != EOF)
switch (c)
{
case OPTION_FORMAT:
switch (*optarg)
{
case 'B':
case 'b':
berkeley_format = 1;
break;
case 'S':
case 's':
berkeley_format = 0;
break;
default:
non_fatal (_("invalid argument to --format: %s"), optarg);
usage (stderr, 1);
}
break;
......
case 0:
break;
......
}
{"format", required_argument, 0, OPTION_FORMAT}
的flag
是NULL
,所以getopt_long
返回值是OPTION_FORMAT
;根据optarg
确定应该使用哪种format
。而{"totals", no_argument, &show_totals, 1}
的flag
非NULL
,getopt_long
返回值是0
,show_totals
的值为1
。
getopt_long
和getopt_long_only
的区别:
getoptlongonly() is like getopt_long(), but ‘-‘ as well as “–” can indicate a long option. If an option that starts with ‘-‘ (not “–“) doesn’t match a long option, but does match a short option, it is parsed as a short option instead.