命令行处理函数getopt_long的使用方法

        getopt_long函数,getopt_long函数具有getopt函数的所有功能,并且还可以指定“长参数”,getopt_long比getopt多了两个参数:

       int getopt_long(int argc, char * const argv[],

                  const char *optstring,

                  const struct option *longopts, int *longindex);

        Longopts指向的是一个由option结构体组成的数组,那个数组的每个元素,指明了一个“长参数”名称和性质:

struct option {
               const char *name;
               //参数的名称
               int         has_arg;
               //指明是否带参数值,其数值可选
               int        *flag;
               //当这个指针为空的时候,函数直接将val的数值从getopt_long的返回值返回出去,当它非空时,val的值会被赋到flag指向的整型数中,而函数返回值为0
               int         val;
               //用于指定函数找到该选项时的返回值,或者当flag非空时指定flag指向的数据的值
           };

      has_arg的数值可选:

      no_argument (0) 表明这个长参数不带参数(不带数值,如:--test)

      required_argument (1) 表明这个长参数必须带参数(必须带数值,如:--test tao)

      optional_argument(2)表明这个长参数后面带的参数是可选的,(--test和--test=zhang均可)

      required_argument(1)时,参数输入格式为:--参数 值:--test tao 或者 --参数=值:--test=tao
      optional_argument(或者是2)时,参数输入格式只能为:--参数=值:--test=tao

      另一个参数longindex,如果longindex非空,它指向的变量将记录当前找到参数符合longopts里的第几个元素的描述,即是longopts的下标值。

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>

char *optstring = "a:b:c:d";
static struct option long_options[] = {
    {"reqarg", required_argument, NULL, 'r'},
    {"noarg",  no_argument,       NULL, 'n'},
    {"optarg", optional_argument, NULL, 'o'},
    {"zhang", optional_argument, NULL, 'z'},
    {"tao", optional_argument, NULL, 't'},
    {"hello", optional_argument, NULL, 'h'},
    {"world", optional_argument, NULL, 'w'},
    {"hik", optional_argument, NULL, 'h'},
    {0, 0, 0, 0}
};

int main(int argc, char **argv)
{
   int opt;
   int digit_optind = 0;
   int option_index = 0;

   while ( (opt = getopt_long(argc, argv, optstring, long_options, &option_index)) != -1)
   {
        printf("%s %d opt = %c\n", __func__, __LINE__, opt);
        printf("%s %d optarg = %s\n", __func__, __LINE__, optarg);
        printf("%s %d optind = %d\n", __func__, __LINE__, optind);
        printf("%s %d argv[optind - 1] = %s\n", __func__, __LINE__,  argv[optind - 1]);
        printf("%s %d option_index = %d\n", __func__, __LINE__, option_index);
   }

   return 0;
}

程序运行结果如下:

        getopt_long_only()这个函数的用法和上一篇的getopt_long完全一样,就是在输入长选项的时候可以不用输入--而使用-,所以对于getopt_long_only来说,--test相当于-test

        在getopt_long中,会将参数-test拆解成-t -e -s -t到optstring中进行匹配,而getopt_long_only只在-test匹配失败的时候,才将其拆解成-t -e -s -t这样的参数到optstring中进行匹配

上一篇:命令行处理函数getopt的使用方法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值