转自:http://speakingbaicai.blog.51cto.com/5667326/1074671
/*
原型:int getopt(int argc, char * const argv[], const char *optstring);
四个全局变量:
extern char *optarg; //指向选项的参数的指针。
extern int optind, //存储位置,下一次调用getopt的时,从optind存储的位置处重新开始检查选项。
extern int opterr, //当opterr=0时,getopt不向stderr输出错误信息。
extern int optopt; //当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt中。
关于optstring:
如: optstring=ab:c::d::时,
1、ab:c::d::的意思是有四个选项-a -b -c -d;
2、其中b c d选项后面有冒号说明b c d后面必须跟参数;
3、b后一个冒号,则参赛和选项之间可有空格,也可没有;
4、c d后面有两个冒号,说明c d后面的参数必须紧跟在选项后面。
如:./a.out -a -b argOfb -cargOfc -dargOfd
如果写成:./a.out -a -b argOfb -c argOfc -dargOfd 则c选项后的参数实际为null
getopt的使用时的主要注意点:
1、getopt每调用一次,返回一个选项,注意是选项不是参数;
2、optarg存放getopt所返回的选项后的参数,选项后没有参数则为null(实际运行时没有或者optstring中的选项后没有:都视为null);
3、当再也检查不到optstring所包含的选项时返回-1;
4、当检查到不在optstring中的选项或缺少必要的参数时,返回?并将该选项存在optopt中。
总结:
在使用时,只需简记getopt返回选项,optarg指向参数即可。
*/
#include <unistd.h>
int main(int argc, char **argv)
{
int opt;
opterr = 0;
while( (opt = getopt(argc, argv, "ab:c::d::")) != -1 )
{
switch(opt)
{
case 'a':
printf("option=a, opt=%d, optarg=%s, optind=%d, optopt=%d\n", opt, optarg, optind, optopt);
break;
case 'b':
printf("option=b, opt=%d, optarg=%s, optind=%d, optopt=%d\n", opt, optarg, optind, optopt);
break;
case 'c':
printf("option=c, opt=%d, optarg=%s, optind=%d, optopt=%d\n", opt, optarg, optind, optopt);
break;
case 'd':
printf("option=d, opt=%d, optarg=%s, optind=%d, optopt=%d\n", opt, optarg, optind, optopt);
break;
case '?':
printf("option=?, opt=%d, optarg=%s, optind=%d, optopt=%d\n", opt, optarg, optind, optopt);
break;
default:
printf("option=default, opt=%d, optarg=%s, optind=%d, optopt=%d\n", opt, optarg, optind, optopt);
break;
}
}
return 0;
}
/*