main函数参数规范

main函数参数规范

给main函数传递参数,非常容易,而且每个人都有自己的编写方式;
这里介绍一下标准C库的getopt规范,该规范定义了两类参数:短参数和长参数

#include <unistd.h>
#include <getopt.h>
/*帮助*/
static void usage(FILE *fp, int argc, char *argv[]) {
	fprintf(fp, "Usage: %s[optionts]\n"
		"Options:\n"
		"-d | --device name 	Video device name[/dev/video]\n"
		"-h | --help 		Print this message\n"
		"", argv[0]);
}
/*短参数*/
static const char short_options[] = "d:h";
/*长参数*/
static const struct option long_options[] = {
	{"device", required_argument, NULL, 'd'},
	{"help", no_argument, NULL, 'h'},
	{0,0,0,0},
};
int main(int argc, char *argv[])
{
	for(;;) {
		int index;
		int c;
		c = getopt_long(argc, argv, short_options, long_options, &index);
		
		if(-1==c)
			break;
		
		switch(c) {
		case 0:
			break;
		case 'd':
			vd->dev_name = optarg;
			break;
		case 'h':
			usage(stdout, argc, argv);
			break;
		default:
			usage(stderr, argc, argv);
			return -1;
		
		}
		
	}

短参数

static const char short_options[] = "d:h";

d:表示d这个标志后面会跟一个具体参数值;
h表示h这个标志后面没有具体参数值;

长参数

static const struct option long_options[] = {`
	{"device", required_argument, NULL, 'd'},
	{"help", no_argument, NULL, 'h'},
	{0,0,0,0},
};

device, required_argument表示有一个具体参数值;
help, no_argument表示没有具体参数值;

引用

int getopt_long(int argc, char * const argv[],
                  const char *optstring,
                  const struct option *longopts, int *longindex);

argc和argv是main函数的参数,直接传入;
optstring,短参数格式定义;
longopts,长参数格式定义;
longindex,参数位置

全局变量optarg,如果某个标志有具体的值,那么参数可以通过optarg直接获得。

深入探讨

请直接在linux命令行中man getopt

#include <unistd.h>
int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;

#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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值