您的位置:首页 > 运维架构 > Linux

Linux之getopt

2016-03-18 14:24 507 查看
研究netmap代码的时候,碰巧就了解了下关于配置参数的问题,促使我去研究的原因是每次安装源代码,需要自己

进行编译链接都会用到./configure,当最后编译链接完成后,若是要运行程序,少不了要在可执行程序后面添加参数,

其中有个最常见的就是 --help,不过这里不讲这个,将一个更简单的  -h ,比如见得最多的 gcc -o 字段  ,那么这个是怎么

实现的呢?

函数getopt很好的解决了这个问题,可通过man手册查看(man 3 getopt)直接看代码:

#include<stdio.h>

#include<unistd.h>

#include<stdlib.h>

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

    int ch; //用来存储选项的ASSIC值

    while((ch = getopt(argc,argv,":hct:")) != -1){                  //":hct:"   的解释可以查看manshouc,简介第一个:表示给出了  -t  但是没有参数时返回:

        printf("optind=%d\n",optind);           //该值是系统定义的变量,初始化值为1,主要指向argv[]的字段,argv[0]为程序名称,从1开始

        printf("option = %c\n",ch);

        switch(ch){

            case 'h':                             //当可执行程序中有  -h  字段是打印帮助信息

                printf("Usage:%s [-h] [-c] [-t argument]\n",argv[0]);

                break;

            case 'c':                            //这个是测试

                printf("%c doesn't have an argument!\n",ch);

                break;

            case 't':

                printf("%c has an argument %s\n",ch,optarg);       //当可执行程序后出现   -t  时其后空格就是其参数,通过系统变量指针optarg获取

                break;

            case '?':                          //当出现的选项不存在时返回?

                printf("the option didn't exsit!\n");

                printf("Usage:%s [-h] [-c] [-t argument]\n",argv[0]);

                break;

            case ':':                           //当出现的选项需要带参数,而实际没有给参数时,返回:    ,可以参考运行结果

                printf("option %s missing an argument!\n",argv[--optind]);

                printf("Usage:%s [-h] [-c] [-t argument]\n",argv[0]);

                optind++;

                break;

        }

    }

    return 0;

}

测试结果如下:

测试一:

[root@localhost tmp]# ./test -c -t test

optind=2

option = c

c doesn't have an argument!

optind=4

option = t

t has an argument test

测试二:

[root@localhost tmp]# ./test -t

optind=2

option = :

option -t missing an argument!

Usage:./test [-h] [-c] [-t argument]

测试三:

[root@localhost tmp]# ./test -l

optind=2

option = ?

the option didn't exsit!

Usage:./test [-h] [-c] [-t argument]

上述就是一个框架,可以根据需求进行添加,更进一步的像--help的实现方法下次有空再更新。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  getopt Linux