getopt和getopt_long参数处理

1:getopt函数

  getopt主要用于解析程序运行时所带的参数,原型如下:

#include <unistd.h>
int getopt(int argc, char * const argv[],const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;

  一般的调用方式:

while((c = getopt(argc, argv, "xy:z::")) != -1){
      switch(c){
      case 'x':   ... ...
      case 'y':   ... ...
      case 'z':   ... ...
      case '?':   ... ... 
      ... ....
      }
}

  参数描述:

  1:argc和argv就是main函数的两个参数

  2:optstring参数是描述可支持选项的字符串,如果某个选项后面需要参数值,则选项后面有一个":"

  3:optarg 正如2所述,它指向了当前选项的参数值

  4:optind 初始值是1,是下一个要解析的argv数组的索引(因为argv[0]是程序本身的名字,所以从1开始)

  5:optopt 初始值为0,当函数解析到不认识的选项时(optstring中未描述的),getopt将会返回字符'?'且将不认识的选项保存在optopt中,并向stderr打印出错信息(也可手动将opterr设置为0就不会打印出来了)

      6:opterr 初始值为1,如果当opterr设置为0时,getopt函数不向stderr输出信息

  参考博客

 

2:getopt_long函数

  getopt_long函数是getopt的一类扩展,用于处理长选项的情况(长选项就是选项值不是一个字符而是一个字符串),原型如下:

#include <getopt.h>
int getopt_long(int argc, char * const argv[],
                  const char *optstring,
                  const struct option *longopts, int *longindex);

  一般调用方式:

    static struct option arg_options[] = {
        {"clientid",    required_argument,    0, 'c'},
        {"foreground",    no_argument,        0, 'f'},
        {"background",    no_argument,        0, 'b'},
        {"hostname",    required_argument,    0, 'H'},
        {"hostname",    required_argument,      0, 'h'},
        {"interface",    required_argument,    0, 'i'},
        {"now",     no_argument,        0, 'n'},
        {"pidfile",    required_argument,    0, 'p'},
        {"quit",    no_argument,        0, 'q'},
        {"request",    required_argument,    0, 'r'},
        {"script",    required_argument,    0, 's'},
        {"version",    no_argument,        0, 'v'},
        {"help",    no_argument,        0, '?'},
        {0, 0, 0, 0}
    };

    /* get options */
    while (1) {
        int option_index = 0;
        c = getopt_long(argc, argv, "c:fbH:h:i:np:qr:s:v", arg_options, &option_index);
        if (c == -1) break;
        switch(c){
        case 'c': ... ...
        ... ...
        }
    }     

  参数描述:

  1:argc、argv、optstring和getopt函数是一样的

  2:longopts 是一个指向struct option的结构体指针,这个结构体在getopt.h头文件是这样定义的:

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

   name: 长选项的名字

     has_arg: 有0,1,2三个值分别对应三个宏no_argumentrequired_argumentoptional_argument,分别表示不要参数和需要参数和参数可有可无

   flag: 决定了getopt_long函数如何返回,如果flag是NULL,getopt_long将返回val的值,否则将返回0(一般设置为NULL)

   val: val值一般是长选项的首字母 

  3:longindex 如果它不是NULL,它将是当前解析的longopts数组的索引值

  注意事项:

  1:其它的外部变量如optarg,optopt,opterr等在getopt_long函数中含义不变

  2:getopt_long接收参数的格式是"--" 而不是 "-"

  3:参数longopts的作用其实是关联短选项和长选项的,所以一个程序的 -c XXX 和 --clientid XXX是同样的效果,只不过长选项提供了更完整的信息给使用者

  参考博客 

原文地址:https://www.cnblogs.com/Flychown/p/6867360.html