Chinaunix首页 | 论坛 | 博客
  • 博客访问: 343446
  • 博文数量: 63
  • 博客积分: 1412
  • 博客等级: 中尉
  • 技术积分: 648
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-10 23:07
文章分类

全部博文(63)

文章存档

2012年(42)

2011年(21)

我的朋友

分类: C/C++

2012-03-06 18:45:49

getopt_long用于得到输入参数。
其中用到的2个重要的全局变量为
(1)optarg-用于输入选项后面的参数
(2)optind-是个索引。标记非选项参数的起始位置。
 
具体getopt_long见如下说明。
头文件  #include
函数原型  int getopt_long(int argc, char * const argv[],
  const char *optstring,
  const struct option *longopts, int *longindex);
函数说明  函数中的argc和argv通常直接从main()到两个参数传递而来。optsting是选项参数组成的字符串,如果该字符串里任一字母后有冒号,那么这个选项就要求有参数。下一个参数是指向数组的指针,这个数组是option结构数组,option结构称为长选项表,其声明如下:
  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,那么会使得它所指向的结构填入val字段的值,同时getopt_long返回0
  int val:
  如果flag是NULL,那么val通常是个字符常量,如果短选项和长选项一致,那么该字符就应该与optstring中
  出现的这个选项的参数相同;
  最后一个参数:longindex参数一般赋为NULL即可;如果没有设置为NULL,那么它就指向一个变量,这个变量
  会被赋值为寻找到的长选项在longopts中的索引值,这可以用于错误诊断。
 
  1. #include <iostream>
  2. #include <getopt.h>

  3. using namespace std;
  4. extern char *optarg;

  5. int    main( int argc, char **argv )
  6. {
  7.     int c = 0;
  8.     struct option long_options[] = {
  9.     {"help", no_argument, 0, 'h'},
  10.     {"version", no_argument, 0, 'v'},
  11.     {"param", required_argument, 0, 'p'},
  12.     {0,0,0,0}
  13.     };

  14.     printf( "optind=[%d]\n", optind );
  15.     while( (c = getopt_long( argc, argv, "hvp:", long_options, NULL ) ) != -1 )
  16.     {
  17.         switch( c )
  18.         {
  19.             case 'h' :
  20.                 cout << "help" << endl;
  21.                 break;
  22.             case 'v' :
  23.                 cout << "version" << endl;
  24.                 break;
  25.             case 'p' :
  26.                 cout << "p:=" << optarg << endl;
  27.                 cout << "p:=" << argv[optind] << endl;
  28.                 break;
  29.             default:
  30.                 cout << "error" << endl;
  31.         };
  32.     }

  33.     for( int i=0; i<argc; i++ )
  34.     {
  35.         cout << argv[i] << endl;
  36.     }

  37.     printf( "optind=[%d]\n", optind );
  38.     printf( "argc=[%d]\n", argc );

  39.     return 0;
  40. }
 
阅读(1218) | 评论(0) | 转发(0) |
0

上一篇:rand7产生rand10

下一篇:c++ static 变量

给主人留下些什么吧!~~