getopt_long函数详解
    一、介绍
    getopt_long函数是linux环境下一个解析命令行参数的函数,它可以自动处理用户输入的参数和参数之间的关联,它支持短参数名称(例如 -v)和长参数名称(例如--verbose)。
    二、函数原型
    getopt_long(int argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex);
    三、参数解释
    (1)argc:main函数参数argc,表示运行时命令行参数的个数
    (2)argv:main函数参数argv,表示运行时命令行参数的内容
    (3)optstring:表示短参数(例如:-v)的参数列表,例如:“vn:”,表示有-v和-n两个参数,-n参数后面跟一个冒号,表示它有一个附加参数
    (4)longopts:表示长参数(例如:--verbose)的参数列表,它是一个结构体类型数组
    (5)longindex:表示实际匹配的长参数在longopts中的位置,如果longindex指针不为NULL,那么在调用getopt_long成功时,会把实际匹配的longopts中的位置赋给longindex。
    四、longopts结构体
    longopts结构体有以下4个元素:
    (1)name:表示长参数名称,例如verbose
    (2)has_arg:表示此长参数后是否跟参数,它必须是以下三个值之一:no_argument(表示没有参数)、required_argument(表示后面必须跟参数)、optional_argument(表示后面可以跟参数)
    (3)flag:表示参数有没有被设置,默认值为NULL
    (4)val:表示参数的值,用于返回给程序,如果flag不为空,那么它的值会被flag指向的变量设置,否则,getopt_long返回val
    五、返回值
    getopt_long函数的返回值有以下几种:
    (1)如果参数匹配成功,那么返回长参数val指定的值
    (2)如果参数匹配失败,那么返回‘?’
    (3)如果发现结尾,那么返回-1
    六、示例
    以下是一个使用getopt_long函数的示例:
    #include <stdio.h>
    #include <stdlib.h>
    #include <getopt.h>
   
    int main(int argc, char *argv[])
    {
    int c;
    int digit_optind = 0;
    int aopt = 0, bopt = 0;
    char *copt = 0;
    char *envi_opt = 0;
   
    while ( (c = getopt(argc, argv, 'ab:c:e:')) != -1) {
    int this_option_optind = optind ? optind : 1;
    switch (c) {
    case 'a':
    printf('option a
    ');
    aopt = 1;
    break;
    case 'b':
    printf('option b with value '%s'
    ', optarg);
    bopt = 1;
    break;
    case 'c':
    printf('option c with value '%s'
    ', optarg);
    copt = optarg;
    break;
    case 'e':
    printf('option e with value '%s'
    ', optarg);
    envi_opt = optarg;
    break;
    case '?':
    break;
    default:
    printf('?? getopt returned character code 0%o ??
    ', c);
    }
    }
   
    if (optind < argc) {
    printf('non-option ARGV-elements: ');
    while (optind < argc)
    printf('%s ', argv[optind++]);
    printf('
库函数printf详解
    ');
    }
   
    exit(EXIT_SUCCESS);
    }
    上面这段代码中使用了“ab:c:e:”这个optstring,表示程序支持-a,-b,-c,-e四个参数,其中-b,-c,-e参数后面跟一个冒号,表示它们都有一个附加参数。
    七、总结
    getopt_long函数是linux环境下一个解析命令行参数的函数,它可以很方便的处理用户输入的短参数和长参数。