getopt如何用

1 getopt()用法

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

这个函数是用来解析命令行的选项的。可是,只能解析短选项,什么是短选项?就是-d这种只有一个-的,并且是只有一个字母的。数组

首先要注意几个外部变量optarg,optind,opterr。函数

opterr设置为0时,当解析命令出错也不向标准输出打印任何信息。ui

optarg是当前解析到的选项的后面带的参数,特别注意必须使用空格来间隔掉选项和后面的值。-d 100,切记只用空格,不要用=。并且getopt只可以解析那些在optstring参数中后面带有了:的选项,如"abcd:"。spa

optind 是指向char *argv[]数组中的当前被处理的参数的下一个位置的指标。能够看做是逾尾指针的性质。命令行

参数详解:optstring这个参数就是用来配置选项参数的。"abcd:",冒号就表示能够带参数。指针

返回值:这个函数直接返回当前解析的短选项的名字,如命令行中为-d,那么这里返回字符d。若是当前全部参数所有解析完,那么此次调用返回-1。通常getopt()函数调用就放在while的判断条件中,直到返回值为-1时为止。code

2 getopt_long()函数

       #include <getopt.h>

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

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

getopt_long()函数能够解析带有长选项参数,如--prefix=/boot/等等,可是若是要禁止使用短参数,则必须将optstring参数设置为空字符串“”。字符串

参数详解:get

longopts 指向struct option结构体数组的第一个元素的指针。注意这个数组的最后一个元素必须是用全0来填充{0,0,0,0}。这个结构体定义在<getopt.h>中。下面看下这个结构体:string

        struct option {
               const char *name;   //这个长选项的名字
               int         has_arg; // 这个长选项可携带的参数的状况,no_argument (or 0  不带参数),required_argument (or 1  须要参数),optional_argument (or 2  可选参数,可带可不带)
               int        *flag;  // 这个成员比较复杂。1 若是设为NULL,那么getopt_long()函数直接返回val的值
               int         val;   //                2 若是不为NULL,那么getopt_long()函数直接返回0,同时,name表示的选项有的话就将val的值赋值给flag指针指向的int变量,name选项没有的话,flag指向的变量维持原状。
           };

3 getopt_long_only()函数与getopt_long的区别

getopt_long_only函数,它与getopt_long函数使用相同的参数表,在功能上基本一致。

    getopt_long只将--name看成长参数,那么对于-name直接当成-n -a -m -e 去解析。

    getopt_long_only会将--name和-name两种选项都看成长参数来匹配,那么对于-name先当作--name来处理,不能匹配时,才去解析为-n -a -m -e。

相关文章
相关标签/搜索