Linux getopt_long函数调用

来源:互联网 发布:docker mysql 连接 编辑:程序博客网 时间:2024/06/06 18:00

       许多Linux应用程序也接受比单字符选项含义更明确的参数。GNU C函数库包括getopt的另一个版本,称为getopt_long(),它接受以双划线(--)开始的长参数。

       与getopt()函数相比,getopt多了两个参数。

一、函数原型

       int  getopt_long(int  argc,   char  *const  argv[],   const  char  *optstring,  const  struct   option  *longopts,  int  *longindex);

1、longopts:指向一个option结构体类型的数组,这个数组的每个元素指明了一个“长参数”的名称和性质等。

       struct option {
               const char *name;
               int         has_arg;
               int        *flag;
               int         val;
       };

a、name:参数的名称

b、has_arg:是否带参数值,其数值可选。其中no_argument (即 0) 表明这个长参数不带参数(即不带数值,如:--name);required_argument (即 1) 表明这个长参数必须带参数(即必须带数值,如:--name Bob);optional_argument(即2)表明这个长参数后面带的参数是可选的,(即--name和--name Bob均可)。

c、flag:当这个指针为空的时候,函数直接将val的数值从getopt_long的返回值返回出去,当它非空时,val的值会被赋到flag指向的整型数中,而函数返回值为0。

d、val:用于指定函数找到该选项时的返回值,或者当flag非空时指定flag指向的数据的值。

2、longindex:如果longindex非空,它指向的变量将记录当前参数对应longopts数组中的第几个元素,即是longopts的下标值。


name  是参数的名称二、范例

#include   <stdio.h>#include   <unistd.h>#include   <stdlib.h>#define     _GNU_SOURCE#include   <getopt.h>int  main(int  argc,   char  *argv[]){      int   opt;      struct   option  longopts[] = {           { "initialize",  0,  NULL,  'i'},           {”file",  1,  NULL,  'f'},           {"list",  0,  NULL,  'l'},           {'restart',  0,  NULL,  'r'},           {0,0,0,0}      };      while((opt = getopt_long(argc,  argv,  ":if:lr",  longopts,  NULL) ) != -1 )      {            switch(opt){                  case  'i':                  case  'l':                  case  'r':                         printf("option:  %c\n", opt);                   break;                                      case  'f':                         printf("filename: %s\n", optarg);                   break;                   case  ':':                         printf("option needs a value\n");                    break;                    case  '?':                         printf("unknown  option:  %c\n",optopt);                    break;      }      for(;optind < argc;  optind++)           printf("argument:  %s\n",argv[optind]);      exit(0);}

注:长选项数组必须以一个包含全0的结构结尾。
 


 

0 0
原创粉丝点击