ACE_Get_Opt解析命令行

 ACE_Get_Opt是一种解析命令行参数选项的迭代器。

  1:构造方法

  ACE_Get_Opt需要引用头文件,#include "ace/Get_Opt.h"。

ACE_Get_Opt (int argc,
               ACE_TCHAR **argv,
               const ACE_TCHAR *optstring = ACE_TEXT (""),
               int skip_args = 1,
               int report_errors = 0,
               int ordering = PERMUTE_ARGS,
               int long_only = 0);

  

  argc、argv为程序入口函数main方法的参数,也就是程序的命令行。

  optstring 为指定的参数选项,并且是一个字符作为一个选项,主要包含三种形式

    • 单纯的一个字符选项,比如 s,表示此选项后面不能添加选项的参数
    • 一个字符选项后跟一个冒号,比如 s:,表示此选项后面会有一个参数
    • 一个字符后面跟两个冒号,比如 s::,表示此选项后面即可以有参数也可以无参数

  skip_args 表示从argv的第几个元素开始,默认为1,一般情况下argv[0]为程序的path

  report_errors遇到不识别的参数时是否提示错误

  long_only表示是否只包含字符串的选项参数。

  下面解释一下 字符选项和字符串选项,也就是 short option 和 long option.

  • short option 以 字符’-’开始,比如 -s
  • long option 以两个字符’-’开始,比入 --server

  这是在默认的情况下,也就是long_only = 0的情况下。而当long_only不等于0的时候,就可以通过-server来表示long option了。

  2:操作

  遍历命令行取出参数项依赖2个基本操作

   /*
   * Scan elements of @a argv (whose length is @a argc) for short option
   * characters given in @a optstring or long options (with no short
   * option equivalents).
   */
   int operator () (void);

   /*
   * For communication from @c operator() to the caller.  When
   * @c operator() finds an option that takes an argument, the argument
   * value is returned from this method, otherwise it returns 0.
   */
  ACE_TCHAR *opt_arg (void) const;

  int operator () (void);用于遍历参数项

  opt_arg用于取出参数项的值。

     3:示例程序

  命令行参数:ACE_TEST.exe -e 2000 -i 1000

#include "ace/Get_Opt.h"
#include "ace/OS_NS_unistd.h"
#include "ace/OS_NS_sys_time.h"

#include <iostream>
const ACE_Time_Value max_interval(60*60);

int main(int argc, char **argv)
{
    ACE_Time_Value expiration = ACE_OS::gettimeofday();
    ACE_Time_Value interval;

    ACE_Get_Opt opt(argc,argv,"e:i:");
    for (int c;(c = opt()) != -1;)
    {
        switch(c)
        {
        case 'e': expiration += ACE_Time_Value(atoi(opt.opt_arg()));
            break;
        case 'i':interval = ACE_Time_Value(atoi(opt.opt_arg()));
            break;
        }
    }
    if (interval > max_interval)
    {
        cout<<"interval must be less than "<<max_interval.sec()<<endl;
    }
    else if (expiration > (ACE_Time_Value::max_time - interval))
    {
        cout<<"expiration + interval must be less than"<<ACE_Time_Value::max_time.sec()<<endl;
    }
    return 0; 
}

  部分转载自http://www.cnblogs.com/hbccdf/p/use_acegetopt_parse_commandline.html。

原文地址:https://www.cnblogs.com/hgwang/p/5868701.html