您的位置:首页 > 编程语言 > C语言/C++

C语言之getopt使用

2016-02-19 20:43 483 查看
在使用开源的程序时,随处可见程序可以接受输入的参数,比如著名的压测工具ab,使用的时候就可以输入如下命令:ab -c 100 -n 10000 http://www.37.com。这样就可以吧客户端数和压测次数传递给ab程序。在c语言中,可以使用int main(int argc,char* argv[]),来获取参数。但是,使用argc和argv这2个变量,有一个缺点,就是需要写大量的代码解析程序参数,其实,在linux下可以使用getopt这个接口来获取参数。

getopt接口:

#include <unistd.h>

int getopt(int argc, char * const argv[], const char *optstring);

extern char *optarg;
extern int optind, opterr, optopt;


getopt参数解析:
argc:就是main的形参argc

argv:就是main的形参argv

optstring:选项字符串,一个字母表示一个短参数,如果字母后带有“:”,表示这个参数必须带有参数。如"c:n:a",则程序可以接受参数"-c 100 -n 1000 -a"

optarg变量:用于获取传入的参数值(如果有)

optind变量:argv的当前索引值。当getopt()在while循环中使用时,循环结束后,剩下的字串视为操作数,在argv[optind]至argv[argc-1]中可以找到。

opterr变量:这个变量非零时,getopt()函数为“无效选项”和“缺少参数选项,并输出其错误信息。

optopt变量:当发现无效选项字符之时,getopt()函数或返回'?'字符,或返回':'字符,并且optopt包含了所发现的无效选项字符。

PS:默认情况下,如果参数错误getopt接口会输出错误参数信息,如果要使用自定义的错误信息,可以将opterr设置为0。

getopt接口可以处理短参数,处理长参数,就要使用getopt_long接口。

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

下面介绍各个参数的含义:

argc、argv是main函数的两个同名的参数。

shortopts选项字符串,一个字母表示一个短参数,如果字母后带有“:”,表示这个参数必须带有参数。如"c:n:a",则程序可以接受参数"-c 100 -n 1000 -a"

longopts是一个struct option结构体的数组,option结构体的定义如下:

struct option{
const char *name;
int has_arg;
int *flag;
int val;
};


name是长选项的名字,has_arg值为0、1、2,分别表示没有参数、有参数、参数可选,flag如果为NULL,函数返回val的值,否则将val的值写入flag指向的变量中,一般情况下,如果flag为NULL,则val的值为该长选项对应的短选项。

longindex参数如果没有设置为NULL,那么它就指向一个变量,这个变量会被赋值为寻找到的长选项在longopts中的索引值,这可以用于错误诊断。

/*
* getopt测试
* 目标:
* 1)程序能接受长参数--number和短参数-n,并打印
* 2)程序能接受长参数--client和短参数-c,并打印
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
//header for getopt
#include<unistd.h>
//header for getopt_long
#include <getopt.h>

static const struct option long_options[] = {
{"number",1,NULL,'n'},
{"clients",1,NULL,'c'}
};

void usage(void);
int main(int argc,char* argv[])
{
//getopt返回值
int opt=0;
<span style="white-space:pre">	opterr=0;//关闭getopt错误信息</span>
while((opt=getopt_long(argc,argv,"n:c:",long_options,NULL))!=-1)
{
//optarg is global
switch(opt)
{
case 'n':
printf("The number is %s\n",optarg);
break;
case 'c':
printf("The clients is %s\n",optarg);
break;
default:
//非法参数处理,也可以使用case来处理,?表示无效的选项,:表示选项缺少参数
usage();
exit(1);
break;

}
}
printf("done!\n");
return 0;
}

void usage(void)
{
printf("Argument error!\n");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: