getopt函数
来源:互联网 发布:a javascript void 编辑:程序博客网 时间:2024/05/16 12:10
getopt 函数的相关介绍
getopt被用来解析命令行选项参数。
#include <unistd.h>
首先说一下什么是选项,什么是参数。
1.单个字符,表示选项,
2.单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。
3 单个字符后跟两个冒号,表示该选项后必须跟一个参数。参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张)。
例如gcc -g -o test test.c ,其中g和o表示选项,test为选项o的参数。
上面是getopt()函数的基本含义,大家懂得了这些之后,我们一个例子加深一下理解。
例如我们这样调用getopt(argc, argv, "ab:c:de::");
从上面我们可以知道,选项a,d没有参数,选项b,c有一个参数,选项e有有一个参数且必须紧跟在选项后不能以空格隔开。getopt首先扫描argv[1]到argv[argc-1],并将选项及参数依次放到argv数组的最左边,非选项参数依次放到argv的最后边。
代码如下:
#include <unistd.h>
#include <stdio.h>
int main(int argc, char * argv[])
{
printf("optind:%d,opterr:%d\n",optind,opterr);
printf("--------------------------\n");
}
执行结果:
shiqi@wjl-desktop:~/code$ vim getopt.c
shiqi@wjl-desktop:~/code$ gcc getopt.c -o g
shiqi@wjl-desktop:~/code$ ./g file1 -a
optind:1,opterr:1
--------------------------
optind: 3,argc:10,argv[3]:-b
HAVE option: -a
optind: 5,argc:10,argv[5]:code
HAVE option: -b
The argument of -b is -c
optind: 7,argc:10,argv[7]:file2
HAVE option: -d
optind: 9,argc:10,argv[9]:file3
HAVE option: -e
The argument of -e is (null)
----------------------------
optind=6,argv[6]=file1
- getopt函数
- getopt()函数
- getopt函数
- getopt函数
- getopt函数
- getopt函数
- getopt()函数
- getopt函数
- getopt函数
- getopt函数
- getopt函数
- getopt函数
- getopt函数
- getopt函数
- getopt函数
- getopt函数
- getopt 函数
- getopt函数
- MySQL常用存储引擎
- [工作交接]Sharp LCDC芯片Goliath2 MSM7227+ANDROID 2.3
- 用ADO进行数据库编程
- 802.11 学习笔记
- DHCP小记
- getopt函数
- eclipse 集成flex
- 【工作交接】 Touch Screen 模拟按键实现
- 设计模式之模版模式
- HTML5学习笔记2013.1.6——新增元素之input元素的类型
- MFC 中ODBC 类 库 简 介
- 90度接线与0度接线
- MFC中如何添加消息响应函数
- 片段