1. 三个函数声明如下:
#include <unistd.h>
int getopt(int argc, char * const argv[], const char* optstring);
#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);
2. getopt函数说明
参数argc和argv是由main()传递的参数个数和内容,argc计算参数的个数是以空格为分隔符的;
参数optstring则表示欲处理的选项字符串,optstring选项字符串可能有以下三种格式的字符:
1.单个字符,表示选项
2.单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg
3 单个字符后跟两个冒号,表示该选项后必须跟一个参数。参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张)。
举例:optstring="a:b::cd",表示选项a还跟有参数,可能以空格隔开,选项b后还跟有参数,直接接在选项后面,选项c,d均无参数。
补充一点,该函数判断是选项或是参数,依据是字符(串)是否是以-开头,如-ab中,-a为选项,b则为参数
3. 此函数影响的全局变量有四个
extern char *optarg; //选项的参数指针
extern int optind, //下一次调用getopt的时,从optind存储的位置处重新开始检查选项。
extern int opterr, //当opterr=0时,getopt不向stderr输出错误信息。
extern int optopt; //当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt中,getopt返回?
4. 一段测试getopt的代码。getopt
#include <stdio.h>
#include <unistd.h>
int main(int argc, char**argv)
{
int ch;
opterr=0; // no printed errors
while((ch=getopt(argc,argv,"a:b:c::d"))!=-1)
switch(ch){
case 'a':
printf("when the option is a, optind=%d, optarg=%s, optopt=%d\n", optind, optarg, optopt);
break;
case 'b':
printf("when the option is b, optind=%d, optarg=%s, optopt=%d\n", optind, optarg, optopt);
break;
case 'c':
printf("when the option is c, optind=%d, optarg=%s, optopt=%d\n", optind, optarg, optopt);
break;
case 'd':
printf("when the option is d, optind=%d, optarg=%s, optopt=%d\n", optind, optarg, optopt);
break;
default:
printf("other options, optind=%d, optarg=%s, optopt=%c\n", optind, optarg, optopt);
}
}
5. get_long()的各种返回值的含义:返回值 含 义
0 getopt_long()设置一个标志,它的值与option结构中的val字段的值一样
1 每碰到一个命令行参数,optarg都会记录它
'?' 无效选项
':' 缺少选项参数
'x' 选项字符'x'
-1 选项解析结束
注:
通过man 3 getopt可以获得更多详细信息。
长选项的好处很多,可以更方便处理各个选项。把option结构体中的第三项初始化为NULL,是一种十分常见的用法。
好文推荐:
UNIX中getopt()使用心得 http://wurb.ycool.com/post.2860683.html
linux getopt_long() http://hi.baidu.com/zhenwl00/blog/item/702501234ec3f8569822edde.html
//文中都有一点小错误,但不影响理解。


浙公网安备 33010602011771号