函数原型
int getopt(int argc, char *const argv[], const char *optstring);
#include <stdio.h>
#include <unistd.h>
extern char *optarg; //指向参数.
extern int optind; //argv下标值,初始化值为1,下一次调用getopt时,从optind存储的位置重新开始检查选项.
extern int opterr; //初始化值为1,当opterr=0时,getopt不向stderr输出错误信息.
extern int optopt; //当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt中,getopt返回'?'.
int main(int argc,char *argv[])
{
int ch;
while((ch=getopt(argc,argv,"a:b::cde"))!=-1)
{
printf("optind:%d\n",optind);
printf("optarg:%s\n",optarg);
printf("ch:%c\n",ch);
switch(ch)
{
case 'a':
printf("option a:'%s'\n",optarg);
break;
case 'b':
printf("option b:'%s'\n",optarg);
break;
case 'c':
printf("option c\n");
break;
case 'd':
printf("option d\n");
break;
case 'e':
printf("option e\n");
break;
default:
printf("default option:%c\n",ch);
}
printf("optopt:%c\n\n",optopt);
}
}
./a.out -a 123 -b456 -c
optind:3
optarg:123
ch:a
option a:'123'
optopt:
optind:4
optarg:456
ch:b
option b:'456'
optopt:
optind:5
optarg:(null)
ch:c
option c
optopt:
1) 单个字符(对应上文中'cde'),表示选项;
2) 单个字符后接一个冒号':'(对应上文中'a:'),表示该选项后必须跟一个参数值,参数紧跟在选项后或者以空格隔开,该参数的指针赋给optarg;
3) 单个字符后跟两个冒号'::'(对应上文中'b::'),表示该选项后必须跟一个参数,参数必须紧跟在选项后不能以空格隔开,该参数的指针赋给optarg。(这个特性是GNU的扩展)。