option structure defined in <getopt.h>

来源:互联网 发布:c语言编程入门编程题 编辑:程序博客网 时间:2024/06/05 15:53


#ifndef __need_getopt
/* Describe the long-named options requested by the application.
   The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector
   of `struct option' terminated by an element containing a name which is
   zero.

   The field `has_arg' is:
   no_argument  (or 0) if the option does not take an argument,
   required_argument (or 1) if the option requires an argument,
   optional_argument  (or 2) if the option takes an optional argument.

   If the field `flag' is not NULL, it points to a variable that is set
   to the value given in the field `val' when the option is found, but
   left unchanged if the option is not found.

   To have a long-named option do something other than set an `int' to
   a compiled-in constant, such as set a value from `optarg', set the
   option's `flag' field to zero and its `val' field to a nonzero
   value (the equivalent single-letter option character, if there is
   one).  For long options that have a zero `flag' field, `getopt'
   returns the contents of the `val' field.  */

struct option
{
  const char *name;
  /* has_arg can't be an enum because some compilers complain about
     type mismatches in all the code that assumes it is an int.  */
  int has_arg;
  int *flag;
  int val;

}



该函数中,初始化结构体数组:const struct option longOptions[],其原型定义在getopt.h中:
#define no_argument 0
#define required_argument 1
#define optional_argument 2

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

const char *name是不带短横线的选项名,前面没有短横线。譬如“help”、“verbose”之类。
int has_arg 描述了选项是否有选项参数。如果有,是哪种类型的参数,此时,它的值一定是下表中的一个。符号常量数值含义
no_argument 0 选项没有参数
required_argument 1 选项需要参数
optional_argument 2 选项参数可选
int *flag 如果这个指针为NULL,那么getopt_long()返回该结构val字段中的数值。如果该指针不为NULL,getopt_long()会使得它所指向的变量中填入val字段中的数值,并且getopt_long()返回0。如果flag不是NULL,但未发现长选项,那么它所指向的变量的数值不变。
int val 这个值是发现了长选项时的返回值,或者flag不是 NULL时载入*flag中的值。典型情况下,若flag不是NULL,那么val是个真/假值,譬如1 或0;另一方面,如果flag是NULL,那么val通常是字符常量,若长选项与短选项一致,那么该字符常量应该与optstring中出现的这个选项的参数相同。
int main(int argc, char *argv[])
{
int opt;
char filename[512];
int open_flag = 0;
while((opt = getopt(argc, argv, “hf:vo")) != -1) {
switch(opt) {
case ‘v': printf(“ver 3.1”);break;
case ‘h':usage();break;
case ‘o’: open_flag =1 ;break;
case 'f':
printf("filename: %s\n", optarg);

strncpy(filename,optarg,sizeof(filename)-1);
break;
case ‘:’:
printf("option %c needs a value\n ", optopt);
break;
case ‘?’:
printf("unknown option: %c\n", optopt);
break;


阅读全文
0 0
原创粉丝点击