http://www.cnblogs.com/sunyubo/archive/2010/09/17/2282120.html
http://vopit.blog.51cto.com/2400931/440453
函数getopt()用来分析命令行参数,其函数原型和相关变量声明如下:
#include
extern char *optarg;
extern int optind, // 初始化值为1,下一次调用getopt时,从optind存储的位置重新开始检查选项,也就是从下一个'-'的选项开始。
extern int opterr, // 初始化值为1,当opterr=0时,getopt不向stderr输出错误信息。
extern int optopt; // 当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt中,getopt返回’?’。
int getopt(int argc, char * const argv[], const char *optstring);
optarg和optind是两个最重要的external
变量。optarg是指向参数的指针(当然这只针对有参数的选项);optind是argv[]数组的索引,众所周知,argv[0]是函数名称,所有参数从argv[1]
开始,所以optind被初始化设置指为1。 每调用一次getopt()函数,返回一个选项,如果该选项有参数,则optarg指向该参数。
在命令行选项参数再也检查不到optstring中包含的选项时,返回-1。
函数getopt()有三个参数,argc和argv[]应该不需要多说,下面说一下字符串optstring,它是作为选项的字符串的列表。
函数getopt()认为optstring中,以'-
’开头的字符(注意!不是字符串!!)就是命令行参数选项,有的参数选项后面可以跟参数值。optstring中的格式规范如下:
1) 单个字符,表示选项,
2) 单个字符后接一个冒号”:”,表示该选项后必须跟一个参数值。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。
3) 单个字符后跟两个冒号”:”,表示该选项后必须跟一个参数。
参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩展)。
- #include
- #include
- int main(int argc,char *argv[])
- {
- int ch;
- opterr=0;
- while((ch=getopt(argc,argv,"a:b::cde"))!=-1)
- {
- printf("/n/n/n");
- 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("other option:%c/n",ch);
- }
- printf("optopt+%c/n",optopt);
- }
- }
定义函数
函数说明
返回值
- #include <stdio.h>
- #include <unistd.h>
- int main(int argc, int *argv[])
- {
- int ch;
- opterr = 0;
- while ((ch = getopt(argc,argv,"a:bcde"))!=-1)
- {
- switch(ch)
- {
- case 'a':
- printf("option a:'%s'\n",optarg);
- break;
- case 'b':
- printf("option b :b\n");
- break;
- default:
- printf("other option :%c\n",ch);
- }
- }
- printf("optopt +%c\n",optopt);
- }
- $ ./getopt -a
- other option :?
- optopt +a
- $ ./getopt -b
- option b :b
- optopt +
- $ ./getopt -c
- other option :c
- optopt +
- $ ./getopt -d
- other option :d
- optopt +
- $ ./getopt -abcd
- option a:'bcd'
- optopt +
- $ ./getopt -bcd
- option b :b
- other option :c
- other option :d
- optopt +
- $ ./getopt -bcde
- option b :b
- other option :c
- other option :d
- other option :e
- optopt +
- $ ./getopt -bcdef
- option b :b
- other option :c
- other option :d
- other option :e
- other option :?
- optopt +f