Linux getopt_long函数调用

       许多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的结构结尾。
 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值