getopt()函数详解
来源:互联网 发布:腾讯软件中心官方网站 编辑:程序博客网 时间:2024/06/05 07:53
getopt()函数是被用来解析命令行选项参数的。
#include <unistd.h> extern char *optarg; //选项的参数指针 extern int optind, //下一次调用getopt的时,从optind存储的位置处重新开始检查选项。 extern int opterr, //当opterr=0时,getopt不向stderr输出错误信息。 extern int optopt; //当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt 中,getopt返回'?’、 int getopt(int argc, char * const argv[], const char *optstring);
选项与参数:
1.单个字符,表示选项。
2.单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。
3.单个字符后跟两个冒号,表示该选项后必须跟一个参数。参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张)。
例如gcc -g -o test test.c ,其中g和o表示选项,test为选项o的参数。
假设现在我们这样调用getopt(argc, argv, "ab:c:de::");
从上面我们可以知道,选项a,d没有参数,选项b,c有一个参数,选项e有有一个参数且必须紧跟在选项后不能以空格隔开。
getopt()首先扫描argv[1]到argv[argc-1],并将选项及参数依次放到argv数组的最左边,非选项参数依次放到argv的最后边。
现在看一个栗子:
int main(int argc,char *argv[]){ int ch; opterr=0; while((ch=getopt(argc,argv,"a:b::cde"))!=-1) { printf("optind:%d\\n",optind); printf("optarg:%s\\n",optarg); printf("optarg:%s\\n",argv[optind]); 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); } return 0;}
编译后,在终端行执行以上的命令:
./a.out -a1234 -b432 -c -d
则会有如下的输出:
optind:2
optarg:1234
ch:a
option a:'1234'
optopt+
optind:3
optarg:432
ch:b
option b:'432'
optopt+
optind:4
optarg:(null)
ch:c
option c
optopt+
optind:5
optarg:(null)
ch:d
option d
optopt+
- getopt函数详解
- getopt,getopt_long函数详解
- 函数getopt()应用详解
- Linux getopt函数详解
- getopt函数详解
- getopt()函数详解
- linux系统getopt函数详解
- getopt与getopt_long函数详解
- linux系统getopt函数详解
- linux之getopt 函数详解
- getopt函数和getopt_long函数详解
- getopt函数详解及__shortopts参数…
- getopt和getopt_long函数使用详解
- 日常笔记之getopt函数详解
- getopt 详解
- getopt详解
- getopt详解
- getopt函数
- struts2学习笔记摘要一
- JavaSE_6th_继承
- nodejs知识点整理
- 超键 主键 候选键 可选键
- activiti工作流常用api
- getopt()函数详解
- C#进阶系列——使用Advanced Installer制作IIS安装包(一:配置IIS和Web.config)
- R6034错误,C Runtime Error
- linux screen 命令详解
- Fiddler简单介绍
- js 去除空格
- hdu 2041 超级楼梯(斐波那契)
- java的注解annotation
- Java和C++在细节上的差异