关于getopt_long函数的学习

来源:互联网 发布:js string 转 double 编辑:程序博客网 时间:2024/05/21 10:06
通过手册查询到getopt_long函数是用来支持长选项的命令行解析的,其声明如下:
int getopt_long(int argc, char * const argv[],const char *optstring, const struct option *longopts,int *longindex);

一时间还是不清楚其用法,通过百度得到如下百度百科信息,在此记录一下

函数中的argc和argv通常直接从main()的两个参数传递而来。optsting是选项参数组成的字符串:
字符串optstring可以下列元素:
1.单个字符,表示选项,
2.单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。
3.单个字符后跟两个冒号,表示该选项后可以有参数也可以没有参数。如果有参数,参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张)。
optstring是一个字符串,表示可以接受的参数。例如,"a:b:cd",表示可以接受的参数是a,b,c,d,其中,a和b参数后面跟有更多的参数值。(例如:-a host --b name)
参数longopts,其实是一个结构的实例:
struct option {
const char *name; //name表示的是长参数名
int has_arg; //has_arg有3个值,分别如下:
                         // 1) no_argument(或者是0),表示该参数后面不跟参数值
                         // 2) required_argument(或者是1),表示该参数后面一定要跟个参数值
                         // 3) optional_argument(或者是2),表示该参数后面可以跟,也可以不跟参数值
int *flag;          //用来决定,getopt_long()的返回值到底是什么。如果flag是null,则函数会返回与该项option匹配的val值
int val;             //和flag联合决定返回值
}

给个例子:
struct option long_options[] = {
{"a123", required_argument, 0, 'a'},
{"c123", no_argument, 0, 'c'},
}
现在,如果命令行的参数是-a 123,那么调用getopt_long()将返回字符'a',并且将字符串123由optarg返回(注意!字符串123由optarg带回!optarg不需要定义,在getopt.h中已经有定义),
那么,如果命令行参数是-c,那么调用getopt_long()将返回字符'c',而此时,optarg是null。最后,当getopt_long()将命令行所有参数全部解析完成后,返回-1。

关于struct option long_options[]结构题的说明,以上面的例子为例:
1) 第1个参数为选项名称——a123/c123,  
2) 第2个参数为1(required_argument)表示选项名称后还带参数,为0(no_argument)表示选项名称后不带参数  
3) 第3个参数是标志,表示返回数据的格式,一般都设为0或NULL  
4) 第4个参数表示该选项的索引值——a/c

范例(来自百度百科):
#include <stdio.h>
#include <getopt.h>

char * l_opt_arg;
char * const short_options = "n:hct:";

struct option long_options[] = {
    { "name", required_argument, NULL, 'n' },
    { "can", 0, NULL, 'c' },
    { "thing", 1, NULL, 't' },
    { "help", no_argument, 0, 'h'},
    { 0, 0, 0, 0},
};
//说明:选项名"name/can/thing/help"是作为--后面的参数,而索引值"n/c/t/h"是最为-后面接的参数

static void usage(char *progname) {
    printf("Usage: %s [options]\n", progname);
    printf("Options:\n");
    printf("  -n, --name        Input you name\n");          
    printf("  -t, --thing        you can do the thing\n");
    printf("  -c, --can        printf 'I can do it!'\n");
    printf("  -h, --help        print the usage\n");
}

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

    while((c =
        getopt_long (argc, argv, short_options, long_options,
        NULL)) != -1) {
        
        switch (c)
        {
            case 'n':
                l_opt_arg = optarg;
                printf("My name is %s.\n", l_opt_arg);
                break;
            case 't':
                l_opt_arg = optarg;
                printf("I can %s.\n", l_opt_arg);
                break;
            case 'c':
                printf("I Can do it!\n");
                break;
            case 'h':
                usage(argv[0]);
                break;
        }
    }

    return 0;
}
 



原创粉丝点击