函数
函数原型
1
int getopt(int argc, char *const argv[], const char * optstring);
函数头文件
1
函数说明
1
2
3
4getopt函数主要用来解析命令行参数; 从其形参argc, argv可以发现是有main()传递的参数个数与内容; 而其第三个参数optsreing 则表示处理选项字符串规则。 以冒号表示参数;
1. 身后不带冒号, 则不需要填充参数
2. 一个冒号,则选项后必须跟有参数
3. 两个冒号,则选项之后的参数是可选的。 若存在参数,参数与选项之间不能存在空格;
示例
a:b:cd::e
这就是一个选项字符串。对应到命令行就是-a
,-b
,-c
,-d
, -e
; 按照上面规则进行分解
不带参数的选项:
c
e
带一个参数的选项:
a
b
可选参数选项:
d
测试代码如下:
1 |
|
测试
正常输入选项
1
2
3
4
5
6[Postgre@yfslcentos71 code]$ ./getopt -a 123 -b1 -c -d -e
options a = 123
options b = 1
options c = (null)
options d = (null)
options e = (null)
不存在选项
1
2
3
4
5
6
7[Postgre@yfslcentos71 code]$ ./getopt -a 123 -b1 -c -d -f
options a = 123
options b = 1
options c = (null)
options d = (null)
./getopt: invalid option -- 'f'
other option : ?
必须带一个参数选项不加参数
1
2
3
4
5[Postgre@yfslcentos71 code]$ ./getopt -a -b1 -c -d -e
options a = -b1
options c = (null)
options d = (null)
options e = (null)
给不带参数选项 添加参数
1
2
3
4
5
6[Postgre@yfslcentos71 code]$ ./getopt -a 12 -b1 -c 34 -d -e 56
options a = 12
options b = 1
options c = (null)
options d = (null)
options e = (null)
可选参数选项
1
2
3
4
5
6
7
8
9
10
11
12
13[Postgre@yfslcentos71 code]$ ./getopt -a 12 -b1 -c -d 1 -e ## 可选参数 与 值 不能加空格
options a = 12
options b = 1
options c = (null)
options d = (null)
options e = (null)
[Postgre@yfslcentos71 code]$
[Postgre@yfslcentos71 code]$ ./getopt -a 12 -b1 -c -d12 -e ## 可选参数 与 值 不能加空格
options a = 12
options b = 1
options c = (null)
options d = 12
options e = (null)