getopt_long函数,getopt_long函数具有getopt函数的所有功能,并且还可以指定“长参数”,getopt_long比getopt多了两个参数:
int getopt_long(int argc, char * const argv[],
const char *optstring,
const struct option *longopts, int *longindex);
Longopts:指向的是一个由option结构体组成的数组,那个数组的每个元素,指明了一个“长参数”名称和性质:
struct option {
const char *name;
//参数的名称
int has_arg;
//指明是否带参数值,其数值可选
int *flag;
//当这个指针为空的时候,函数直接将val的数值从getopt_long的返回值返回出去,当它非空时,val的值会被赋到flag指向的整型数中,而函数返回值为0
int val;
//用于指定函数找到该选项时的返回值,或者当flag非空时指定flag指向的数据的值
};
has_arg的数值可选:
no_argument (0) 表明这个长参数不带参数(不带数值,如:--test)
required_argument (1) 表明这个长参数必须带参数(必须带数值,如:--test tao)
optional_argument(2)表明这个长参数后面带的参数是可选的,(--test和--test=zhang均可)
required_argument(1)时,参数输入格式为:--参数 值:--test tao 或者 --参数=值:--test=tao。
optional_argument(或者是2)时,参数输入格式只能为:--参数=值:--test=tao。
另一个参数longindex,如果longindex非空,它指向的变量将记录当前找到参数符合longopts里的第几个元素的描述,即是longopts的下标值。
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
char *optstring = "a:b:c:d";
static struct option long_options[] = {
{"reqarg", required_argument, NULL, 'r'},
{"noarg", no_argument, NULL, 'n'},
{"optarg", optional_argument, NULL, 'o'},
{"zhang", optional_argument, NULL, 'z'},
{"tao", optional_argument, NULL, 't'},
{"hello", optional_argument, NULL, 'h'},
{"world", optional_argument, NULL, 'w'},
{"hik", optional_argument, NULL, 'h'},
{0, 0, 0, 0}
};
int main(int argc, char **argv)
{
int opt;
int digit_optind = 0;
int option_index = 0;
while ( (opt = getopt_long(argc, argv, optstring, long_options, &option_index)) != -1)
{
printf("%s %d opt = %c\n", __func__, __LINE__, opt);
printf("%s %d optarg = %s\n", __func__, __LINE__, optarg);
printf("%s %d optind = %d\n", __func__, __LINE__, optind);
printf("%s %d argv[optind - 1] = %s\n", __func__, __LINE__, argv[optind - 1]);
printf("%s %d option_index = %d\n", __func__, __LINE__, option_index);
}
return 0;
}
程序运行结果如下:
getopt_long_only()这个函数的用法和上一篇的getopt_long完全一样,就是在输入长选项的时候可以不用输入--而使用-,所以对于getopt_long_only来说,--test相当于-test
在getopt_long中,会将参数-test拆解成-t -e -s -t到optstring中进行匹配,而getopt_long_only只在-test匹配失败的时候,才将其拆解成-t -e -s -t这样的参数到optstring中进行匹配