关于 C 语言中使用库函数 getopt 解析命令行参数的使用方法

       
著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

可以解析短参数,所谓短参数就是指选项前只有一个“-”的情况。

getopt函数

#include
int getopt(int argc,char * const argv[],const char *optstring);

extern char *optarg;   //当前选项参数字串
extern int optind;     //argv的当前索引值(下文会详细介绍)

各参数的意义:

argc: 通常为main函数中的argc
argv: 通常为main函数中的argv
optstring: 用来指定选项的内容(如:"ab:c"),它由多个部分组成,表示的意义分别为:

  1. 单个字符,表示选项。
  2. 单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。
  3. 单个字符后跟两个冒号,表示该选项后可以跟一个参数,也可以不跟。如果跟一个参数,参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。

调用该函数将返回解析到的当前选项,该选项的参数将赋给optarg,如果该选项没有参数,则optarg为NULL。

一、getopt 函数的一般使用

新建文件 test.c,并在文件中输入以下内容:

#include 
#include 
#include 

int main(int argc, char *argv[]) {
    int opt = 0;
    while ((opt = getopt(argc, argv, "ab:c::")) != -1) {
        switch (opt) {
            case 'a':
                printf("option a: %s\n", optarg);  // 在这里 optarg == NULL 是成立的
                break;
            case 'b':
                printf("option b: %s\n", optarg);
                break;
            case 'c':
                printf("option c: %s\n", optarg);
                break;
        }
    }
    return 0;
}

执行如下命令进行编译:

gcc test.c -o test

运行命令及得到相应结果如下:
命令1

./test -a -b 123

结果1

option a: (null)
option b: 123

命令2

./test -a -b 123 -c

结果2

option a: (null)
option b: 123
option c: (null)

命令3

./test -a -b 123 -cbubble

结果3

option a: (null)
option b: 123
option c: bubble

二、注意点

1、getopt 函数解析完命令行中的最后一个参数后,argv 中的参数顺序将会发生改变——执行的文件名仍然排在最前面,接下来的部分是选项及其参数,最后是其他参数。如执行的命令为

./test -a value -b 123 key -cbubble

输出结果仍然为

option a: (null)
option b: 123
option c: bubble

如果没有使用 getopt 函数解析命令行参数的话,argv 中的内容应该如下,

argv[0] = "./test"
argv[1] = "-a"
argv[2] = "value"
argv[3] = "-b"
argv[4] = "123"
argv[5] = "key"
argv[6] = "-cbubble"

然而,由于这里受到了 getopt 函数的影响,argv 中的实际内容如下,

argv[0] = "./test"
argv[1] = "-a"
argv[2] = "-b"
argv[3] = "123"
argv[4] = "-cbubble"
argv[5] = "value"
argv[6] = "key"

2、上面提到的 while 循环在结束后,除了 argv 中的参数位置会发生变化外,还会将 optind 变量指向第一个不是选项也不是选项参数的参数,如对于上述提到的参数位置发生变化的 argv,optind 指向 "value" 的位置。

你可能感兴趣的:(关于 C 语言中使用库函数 getopt 解析命令行参数的使用方法)