1 getopt
#include <unistd.h>
int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
argc argv是main函数的参数,optstring定义了命令行的使用方法。
比如你想这样使用一个命令:
./a.out -t test -d
optstring就可以指定为:"t:d"。t后面加冒号表示选项后面有参数,如果加两个冒号,表示参数是可选的,不加就是没有参数。获取到的参数会保存在optarg里面。该函数从argv[optind]开始检测,默认的,optind被设置为1.遇到非法的情况,比如某选项后面应该跟一个参数,但是命令行没有解析到,就会有错误的提示信息输出。将opterr 置为0就不会输出。如果解析到不能识别的选项,会提示错误信息,并将该字符保存到optopt里面,该函数返回'?'或者':'(如果第一个字符是':').正常情况下该函数返回选项的字母,即传递给optsting的对应的字母。解析结束时,返回-1.
实例如下:
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
int main(int argc, char **argv)
{
char ch = 0;
opterr = 0;
while((ch = getopt(argc,argv,"a:b::")) != -1)
{
switch(ch)
{
case 'a':
std::cout << " a " << std::endl;
if(optarg[0] == ':')
std::cout << "optstr[0] == :" << std::endl;
else
std::cout << "optstr=" << optarg << std::endl;
break;
case 'b':
std::cout << " b " << std::endl;
break;
case ':'
case '?':
printf("optopt = %c/n",optopt);
break;
default:
;
}
}
return 0;
}
注意,该函数有bug,比如命令如下:
./a.out -a -b
假设-a需要指定参数,而用户忘记指定参数了,就直接跟了选项-b,那么该函数不会出错,optarg的值为-b,这种情况需要我们自行判断每个选项的参数。
2 getopt_long
#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);
该函数允许这样的命令行调用:
./a.out --start oss
长的选项通过结构体option指定:
struct option {
const char *name; //选项的名称
int has_arg; //1表示有参数,0表示没有
int *flag; //如果如NULL,检测到name时,函数的返回值为val.否则返回0,当检测到name时,val被置为flag所指向的变量。
int val;
};
要求使用时传递一个option的数组,并且该数组的最后一个option各项均为0.
如果longindex非空,函数返回时,longopt[longindex]指向了当前检测到的选项。
optstring表示使用的短选项,如果只允许使用长选项,该数组置为"".
使用时短选项由optstring指定,长选项由longopt指定,假如使用的命令如下:
./a.out -a addr --start t
检测到短选项-a时,函数返回值与getopt相同,检测到--start时,函数返回值与flag的设定有关。
getopt_long_only函数意味着使用--start时可以直接-start来指定。并且,对于检测的数优先去与长选项的数组进行匹配。
当有未知选项时,返回0.
示例如下:
#include <stdio.h>
#include <getopt.h>
int main(int argc, char **argv)
{
int c = 0;
int index = 0;
struct option long_opt[] = {
{"start",1,NULL,1},
{"stop",1,NULL,2},
{"add",1,NULL,'a'},
{0,0,0,0}
};
while((c = getopt_long_only(argc,argv,"S:",long_opt,&index)) != -1)
{
switch(c)
{
case 0:
printf("option %s/n",long_opt[index].name);
if(optarg)
printf("arg %s/n",optarg);
break;
case 'a':
printf("option add/n");
break;
case 1:
printf("option start/n");
break;
case 2:
printf("option stop/n");
break;
case 'S':
printf("option S/n");
break;
case '?':
break;
default:
printf("ret = %c/n",c);
}
}
return 0;
}