getopt

函数

  • 函数原型

    1
    int getopt(int argc, char *const argv[], const char * optstring);
  • 函数头文件

    1
    #include <unistd.h>
  • 函数说明

    1
    2
    3
    4
    getopt函数主要用来解析命令行参数; 从其形参argc, argv可以发现是有main()传递的参数个数与内容; 而其第三个参数optsreing 则表示处理选项字符串规则。 以冒号表示参数; 
    1. 身后不带冒号, 则不需要填充参数
    2. 一个冒号,则选项后必须跟有参数
    3. 两个冒号,则选项之后的参数是可选的。 若存在参数,参数与选项之间不能存在空格;



示例

a:b:cd::e这就是一个选项字符串。对应到命令行就是-a ,-b ,-c ,-d, -e ; 按照上面规则进行分解

  • 不带参数的选项:c e

  • 带一个参数的选项: a b

  • 可选参数选项: d

测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <stdio.h>
#include <unistd.h>

int main(int argc, char*argv[])
{
int ch;

while((ch = getopt(argc, argv, "a:b:cd::e")) != -1)
{
switch(ch)
{
case 'a':
printf("options a = %s\n", optarg);
break;
case 'b':
printf("options b = %s\n", optarg);

break;
case 'c':

printf("options c = %s\n", optarg);
break;
case 'd':

printf("options d = %s\n", optarg);
break;
case 'e':

printf("options e = %s\n", optarg);
break;

default :
printf("other option : %c\n", ch);
}
}

return 0;
}

测试

  • 正常输入选项

    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)
欣赏此文? 求鼓励,求支持!