get_optional_long
get_optional_long用来获取启动选项
int getopt_long (int argc, char * *argv,
const char *shortopts,
const struct option *longopts,
int *longind)
argc: 参数个数
argv: 参数列表
shortopts:选项短名称,比如a:b::c
(x 对应option结构中的no_argument,使用-x传参
x: 对应option结构中的required_argument,使用-x=value传参
x:: 对应option结构中的optional_argument, 可以使用-x传参,也可以使用-x=value传参)
longopts:选项长名称
option结构
struct option
{
const char *name; // 启动选项长名称,使用--xxx或--xxx=value传值
int has_arg; // 选项类型
// #define no_argument 0
// #define required_argument 1
// #define optional_argument 2
int *flag;
int val; // 启动选项短名称
};
返回值
成功返回选项短名称,失败返回-1
optind
启动选项序号
optarg
启动选项的值
测试代码
#include "getopt.h"
#include <cstdio>
int main(int argc, char const *argv[])
{
struct option longopts[] = {
{"add", required_argument, nullptr, 'a'},
{"delete", required_argument, nullptr, 'd'},
{"modify", required_argument, nullptr, 'm'},
{"help", no_argument, nullptr, 'h'},
{0, 0, 0, 0}}; //最后一行使用0填充
int opt;
int index;
while ((opt = getopt_long(argc, (char *const *)argv, "a:d:m:h", longopts, &index)) != -1) //循环获取每个启动选项的值
{
switch (opt)
{
case 'a':
printf("Input %d parameter is -a=%s\n", optind, optarg);//optarg就是启动选项a的值
break;
case 'd':
printf("Input %d parameter is -d=%s\n", optind, optarg);
break;
case 'm':
printf("Input %d parameter is -m=%s\n", optind, optarg);
break;
case 'h':
printf("Input %d parameter is -h=%s\n", optind, optarg);
break;
default:
printf("unknown %c\n", opt);
break;
}
}
return 0;
}