参数解析函数getopt

  今天看到了遇到了一个很好的unix参数解析函数getopt(),记录一下:

函数原型

int getopt(int argc, char *const *argv, const char *options)

  这个函数被定义在头文件<unistd.h>中,同时头文件中定义了四个与这个函数有关变量。

  int opterr: 控制是否将遇到错误信息(缺少参数等)打印到stderr。当这个值被赋予非零(或者使用default)的时候会打印错信息到stderr,当这个值被赋予0时则不打印错误信息。

  int optopt: 当getopt遇到一个未知参数或者参数缺少必要参数值时,会将参数记录在optopt。保存的这个参数可以被用户用来错误处理。

  int optind: 一个索引,指向下一个没有被getopt中options匹配到的值,可以用这个参数来记录non-options的开始。初始值为1。

  char *optarg: 指向option后面的参数。

 

函数返回值  

  正常返回option character;

  no more option arguments返回 -1;

  非法option返回character '?';

 

Demo

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<ctype.h>
int main(int argc,char ** argv)
{
        int c,index;
        int aflag;
        char * bvalue =NULL, *cvalue=NULL;

        opterr =0;
        while((c=getopt(argc, argv,"ab:c::"))!=-1)    //a不跟参数(无冒号),b一定有参数(单冒号),c后面参数可有可无(双冒号)
                switch(c)
                {
                        case 'a':
                                aflag=1;
                                break;
                        case 'b':
                                bvalue=optarg;
                                break;
                        case 'c':
                                cvalue=optarg;
                                break;
                        case '?':
                               if(optopt == 'c')
                               fprintf(stderr,"Option -%c require an argument.\n",optopt);
                               else if(isprint(optopt))
                                fprintf(stderr,"Unknow '-%c'.\n",optopt);
                               else
                                fprintf(stderr,"Unknow option character'\\x%x.\n'",optopt);
                         return 1;
                        default:
                                abort();
                }
        printf("aflag=%d\nbvalue=%s\ncvalue=%s\n",aflag,bvalue,cvalue);
        for(index=optind; index<argc; index++)
        {
                printf("Non-option argument %s\n", argv[index]);
        }
        return 0;
}

 

    

参考文献:

https://www.gnu.org/software/libc/manual/html_node/Getopt.html#Getopt

posted @ 2018-02-05 23:41  kpliu  阅读(96)  评论(0编辑  收藏  举报