作用:获取解析程序运行时用户输入的外部传参(例如:输入ls时的-a、-l的短参,还有--help、-help长参。)
函数原型
#include
int getopt(int argc, char * const argv[],const char *optstring);
extern char *optarg; //存储选项的参数
extern int optind //指向下一个扫描的位置
, opterr //是否显示错误信息
, optopt; //读取到的字符如果不在opstring(上面例子是"alRtS")中,则存入optopt中
#include
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);
函数说明
getopt():是获取短参数的,它可以获取-a,-l类型的短参数,也可以-al合并的获取到a和l。
getopt_long():是在getopt()的基础上获取长参数,它还可以获取--help这种参数。
getopt_long_only():也是在上一个函数基础上有所增加,输入长参数可以不用输入两个--,而是这样:-help。
argc和argv即传给main()函数的参数,函数如果读取结束会返回-1,否则返回对应的字符。
optstring:"abc:d:012",这里的一个冒号代表这个冒号前面这个字符出现时需要有参数,例如这样ls -a5,那个这个5就是一个参数,"c::"那么就是说c可以带参数也可以不带
长选项表:
struct option
{
const char *name;//name长选项的名字
int has_arg;//has_arg如果选项没有参数这一项是no_argument者0;如果有参数那么是required_argument或者1;如果参数是可选的是optional_argument或者2
int *flag;//flag如果为NULL,getopt_long()返回该结构val字段中的数值;如果不为NULL,getopt_long()会使得flag所指向的变量中填入val字段中的数值,并且getopt_long()返回0;通常flag设置为NULL,val设置为与该长选项对应的短选项
int val;//val一个值,一般写成长选项所对应的短选项
};
getopt示例
//录入参数
char opt;
opterr = 0; //不显示参数错误信息
while ((opt = getopt(argc,argv,"alRtS")) != -1) {
if (opt == 'a') {
param |= PARAM_a;
} else if (opt == 'l') {
param |= PARAM_l;
} else if (opt == 'R') {
param |= PARAM_R;
} else if (opt == 'S') {
param |= PARAM_S;
} else if (opt == 't') {
param |= PARAM_t;
} else {
printf("对不起,目前只支持参数R,S,a,t和l.\n");
exit(0);
}
}
getopt_long_only示例
#include
#include
#include
int main(int argc, char **argv)
{
int c;
int digit_optind = 0;
int this_option_optind = optind ? optind : 1;
int option_index = 0;
static struct option long_options[] = {
{"add", required_argument, 0, 0 },
{"append", no_argument, 0, 0 },
{"delete", required_argument, 0, 0 },
{"verbose", no_argument, 0, 0 },
{"create", required_argument, 0, 'c'},
{"file", required_argument, 0, 0 },
{0, 0, 0, 0 }
};
while (1) {
c = getopt_long_only(argc, argv, "abc:d:012",
long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
printf("option %s", long_options[option_index].name);
if (optarg)
printf(" with arg %s", optarg);
printf("\n");
break;
case '0':
case '1':
case '2':
if (digit_optind != 0 && digit_optind != this_option_optind)
printf("digits occur in two different argv-elements.\n");
digit_optind = this_option_optind;
printf("option %c\n", c);
break;
case 'a':
printf("option a\n");
break;
case 'b':
printf("option b\n");
break;
case 'c':
printf("option c with value '%s'\n", optarg);
break;
case 'd':
printf("option d with value '%s'\n", optarg);
break;
case '?':
break;
default:
printf("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind < argc) {
printf("optind:%d\n",optind);
printf("non-option ARGV-elements: ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
exit(EXIT_SUCCESS);
}