Linux c中使用 getopt_long 处理输入参数

getopt_long

reference: linux manual man getopt_long
#include <getopt.h>
int getopt_long(int argc, char * const argv[],
const char *optstring,
const struct option *longopts, int *longindex);
optstring:短选项字符串
longopts指针指向 struct option 数组的第一个元素
longindex是 struct option 数组的索引
struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
*name 长选项
has_arg 有三种方式:no_argument/required_argument/optional_argument
*flag: 一般设定为NULL,而且把val的值设置成跟短选项一样的值
val:长选项在被解析的时候返回的值,或者是加载flag所指向的变量。

/*************************************************************************
	> File Name: getopt_long.c
	> Author:Maobin
	> Mail:
	> Created Time: 2020年03月14日 星期六 22时00分44秒
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<getopt.h>
#include<string.h>
void usage()
{
	printf("Usage:\n"
		"--help -h\n"
		"--width -w\n"
		"--height -h\n"
		"--format -f\n");
}
static struct option const long_options[] =
{
	{"help", no_argument, NULL, 'H'},
	{"height", required_argument, NULL, 'h'},
	{"width", required_argument, NULL, 'w'},
	{"format", required_argument, NULL, 'f'},
	{NULL, 0, NULL, 0}
};
int parse_args();
int parse_args(int argc,char **argv)
{
	int c;
	int width=0;
	int height=0;
	int longindex=0;
	char format[64]="NV12";
	while ((c = getopt_long (argc, argv, "Hh:w:f:", long_options, &longindex)) != -1)
	{
		switch (c)
		{
			case 'h':
				height=atoi(optarg);
				break;
			case 'w':
				width=atoi(optarg);
				break;
			case 'f':
				memset(format,0,sizeof(format));
				sprintf(format,"%s",optarg);
				break;
			case 'H':
				usage();
				exit(0);
			case '?':
				usage();
				exit(0);
			default:
				usage();
				exit(0);
		}
	}
	printf("format: %s\n",format);
	printf("width: %d\n",width);
	printf("height: %d\n",height);
	return 0;
}
int main(int argc, char **argv)
{

	printf("%s\n","Hello World!");
	parse_args(argc,argv);
	return 0;
}

执行结果:
在这里插入图片描述

发布了4 篇原创文章 · 获赞 3 · 访问量 1461

猜你喜欢

转载自blog.csdn.net/hemaobin/article/details/104874367
今日推荐