如何利用ACE_Get_Opt理会呼吁行
当前位置:以往代写 > C/C++ 教程 >如何利用ACE_Get_Opt理会呼吁行
2019-06-13

如何利用ACE_Get_Opt理会呼吁行

如何利用ACE_Get_Opt理会呼吁行

副标题#e#

当我们用C++开拓一些C++节制台小东西时,会需要一些用户输入的参数来抉择措施如何事情和执行,而用户输入参数的方法大部门都是回收呼吁行参数的方法。

好比上一篇文章 玩转Windows处事系列——呼吁行打点Windows处事 中先容的sc和net东西。

既然呼吁行参数这么普遍也这么有用,那么就有须要进修一下如何理会呼吁行参数。

如何理会呼吁行参数

那么呼吁行参数要如何理会呢。

最最最笨的步伐就是每次措施中需要理会呼吁行参数时,就写一堆理会的代码,可是这样的效率其实很低的,不如利用开源库中的辅佐类来理会。

我所相识的开源库的辅佐类有

ACE库的ACE_Get_Opt

boost的Program_options

ACE_Get_Opt类的主要利用要领先容

那么我们主要看一下ACE_Get_Opt类

先看它的结构要领

CollapseACE_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);

下面是代码中的注释

Collapse/**
* Constructor initializes the command line to be parsed. All information
* for parsing must be supplied to this constructor.
*
* @param argc          The number of @a argv elements to parse.
* @param argv          Command line tokens, such as would be passed
*                      to @c main().
* @param optstring     Nul-terminated string containing the legitimate
*                      short option characters.  A single colon ":"
*                      following an option character means the option
*                      requires an argument.  A double colon "::" following
*                      an option character means the argument is optional.
*                      The argument is taken from the rest of the current
*                      @a argv element, or from the following @a argv
*                      element (only valid for required arguments;
*                      optional arguments must always reside in the same
*                      @a argv element). The argument value, if any is
*                      returned by the @c opt_arg() method.
*                      @a optstring can be extended by adding long options
*                      with corresponding short options via the
*                      @c long_option() method.  If the short option
*                      already appears in @a optstring, the argument
*                      characteristics must match, otherwise it is added.
*                      See @c long_option() for more information.
*                      If 'W', followed by a semi-colon ';' appears in
*                      @a optstring, then any time a 'W' appears on the
*                      command line, the following argument is treated as
*                      a long option.  For example, if the command line
*                      contains "program -W foo", "foo" is treated as a
*                      long option, that is, as if "program --foo" had
*                      been passed.
*                      The following characters can appear in @a optstring
*                      before any option characters, with the described
*                      effect:
*                      - '+' changes the @a ordering to @a REQUIRE_ORDER.
*                      - '-' changes the @a ordering to @a RETURN_IN_ORDER.
*                      - ':' changes the return value from @c operator()
*                            and get_opt() from '?' to ':' when an option
*                            requires an argument but none is specified.
*
* @param skip_args     Optional (default 1). The specified number of
*                      initial elements in @a argv are skipped before
*                      parsing begins. Thus, the default prevents
*                      @a argv[0] (usually the command name) from being
*                      parsed. @a argc includes all @a argv elements,
*                      including any skipped elements.
* @param report_errors Optional, if non-zero then parsing errors cause
*                      an error message to be displayed from the
*                      @c operator() method before it returns. The
*                      error message is suppressed if this argument is 0.
*                      This setting also controls whether or not an error
*                      message is displayed in @c long_option() encounters
*                      an error.
* @param ordering      Optional (default is @c PERMUTE_ARGS); determines
*                      how the @a argv elements are processed. This argument
*                      is overridden by two factors:
*                      -# The @c POSIXLY_CORRECT environment variable. If
*                         this environment variable is set, the ordering
*                         is changed to @c REQUIRE_ORDER.
*                      -# Leading characters in @a optstring (see above).
*                         Any leading ordering characters override both
*                         the @a ordering argument and any effect of the
*                         @c POSIXLY_CORRECT environment variable.
* @param long_only     Optional. If non-zero, then long options can be
*                      specified using a single '-' on the command line.
*                      If the token is not a long option, it is processed
*                      as usual, that is, as a short option or set of
*                      short options.
*
* Multiple short options can be combined as long as only the last
* one can takes an argument. For example, if @a optstring is defined as
* @c "abc:" or @c "abc::" then the command line @e "program -abcxxx" short
* options @e a, @e b, and @e c are found with @e "xxx" as the argument for
* @e c.
* However, if the command line is specified as @e "program -acb" only
* options @e a and @e c are found with @e "b" as the argument for @e c.
* Also, for options with optional arguments, that is, those followed by
* "::", the argument must be in the same @a argv element, so "program -abc
* xxx" will only find "xxx" as the argument for @e c if @a optstring is
* specified as @c "abc:" not @c "abc::".
*/


#p#副标题#e#

结构函数共有七个参数,

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了。

那么来看一个界说的例子

ACE_Get_Opt opt(argc, argv, "s:u:p:", 1, 0);

三个重载要领long_option的先容

由于结构要领中的optstring只能拟定short option,所以必需通过long_option要领来指定long option。

ACE_Get_Opt类中有三个重载的long_option要领,下面来一一先容

#p#分页标题#e#

long_option要领一:

Collapse/// Adds a long option with no corresponding short option.
/**
 * If the @a name option is seen, @c operator() returns 0.
 *
 * @param name          The long option to add.
 * @param has_arg       Defines the argument requirements for
 *                      the new option.
 *
 * @retval 0  Success
 * @retval -1 The long option can not be added.
 */
int long_option (const ACE_TCHAR *name,
                 OPTION_ARG_MODE has_arg = NO_ARG);

这个要领可以增加long_option,第一个参数name暗示要添加的option的名字,第二个参数暗示这个option是否包括参数,下面是OPTION_ARG_MODE的界说:

Collapse/// Mutually exclusive option argument mode used by long options.
enum OPTION_ARG_MODE
{
  /// Doesn't take an argument.
  NO_ARG = 0,
    
  /// Requires an argument, same as passing ":" after a short option
  /// character in @a optstring.
  ARG_REQUIRED = 1,
    
  /// Argument is optional, same as passing "::" after a short
  /// option character in @a optstring.
  ARG_OPTIONAL = 2
};

NO_ARG暗示没有参数,对应short option中的没有冒号的环境

ARG_REQUIRED暗示必需有参数,对应short option中有一个冒号的环境

ARG_OPTIONAL暗示参数无关紧要,对应short option中有两个冒号的环境

此要领可以这样利用

if(opt.long_option("server", ACE_Get_Opt::ARG_REQUIRED) == -1)
{
  cout << "server option can not be added" << endl;
}

#p#副标题#e#

long_option要领二:

Collapse/// Adds a long option with a corresponding short option.
  /**
   * @param name          The long option to add.
   * @param short_option  A character, the short option that corresponds
   *                      to @a name.
   * @param has_arg       Defines the argument requirements for
   *                      the new option.  If the short option has already
   *                      been supplied in the @a optstring, @a has_arg
   *                      must match or an error is returned; otherwise, the
   *                      new short option is added to the @a optstring.
   *
   * @retval 0  Success
   * @retval -1 The long option can not be added.
   */
  int long_option (const ACE_TCHAR *name,
                   int short_option,
                   OPTION_ARG_MODE has_arg = NO_ARG);

#p#分页标题#e#

这个要领中增加了一个short_option参数,暗示这个long_option与对应的short_option所表达的意义是一致的,当理会呼吁行时,碰着这个long_option时,就按此处的short option举办处理惩罚。

此要领可以这样利用

if(opt.long_option("server", 's', ACE_Get_Opt::ARG_REQUIRED) == -1)
{
  cout << "server option can not be added" << endl;
}

long_option要领三:

/// Returns the name of the long option found on the last call to
  /// @c operator() or 0 if none was found.
  const ACE_TCHAR *long_option (void) const;

这个要领暗示理会呼吁行时,假如碰着long_option,则可以通过这个要领来获取是哪一个long_option。

呼吁行的理会

呼吁行的理会就要依赖 operator()()要领,和opt_arg要领,前者理会碰着的是哪个short option 可能 long option,而 opt_arg要领例获取option的参数。

下面看一下要领的声明

Collapse/**
 * 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).
 *
 * If an element of @a argv starts with '-', and is not exactly "-"
 * or "--", then it is a short option element.  The characters of this
 * element (aside from the initial '-') are option characters. If
 * it starts with "--" followed by other characters it is treated as
 * a long option.  If @c operator() is called repeatedly, it returns
 * each of the option characters from each of the option elements.
 *
 * @return The parsed option character. The following characters have
 * special significance.
 * @retval 0      A long option was found
 * @retval '\?'   Either an unknown option character was found, or the
 *                option is known but requires an argument, none was
 *                specified, and @a optstring did not contain a leading
 *                colon.
 * @retval ':'    A known option character was found but it requires an
 *                argument and none was supplied, and the first character
 *                of @a optstring was a colon. @c opt_opt() indicates
 *                which option was specified.
 * @retval '1'    @c RETURN_IN_ORDER was specified and a non-option argument
 *                was found.
 * @retval EOF No more option characters were found.  @c opt_ind() will
 *             return the index in @a argv of the first @a argv element
 *             that is not an option.  If @c PERMUTE_ARGS was
 *             specified, the @a argv elements have been permuted so that
 *             those that are not options now come last.
 *
 * @note The standards are unclear with respect to the conditions under
 * which '?' and ':' are returned, so we scan the initial characters of
 * @a optstring up unto the first short option character for '+', '-',
 * and ':' in order to determine ordering and missing argument behavior.
 */
int operator () (void);
Collapse/**
 * 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;

operator()要领有几种返回值:

详细的option 字符,暗示呼吁行中碰着了此 short option,可能关联了short option的 long option

0,暗示碰着了一个long option,可以通过上面先容的long_option的要领三来获取一下详细是哪一个long option

EOF,也就是-1,暗示理会竣事。

当operator()要领返回一个short option可能 long option时,假如这个option可以有参数,则通过opt_arg要领来获取详细的参数。

#p#副标题#e#

完整的呼吁行理会代码

下面展示一个完整可是较量简朴的呼吁行理会的示例措施代码

Collapse#include "ace/Get_Opt.h"
#include <iostream>
using namespace std;
    
    
int _tmain(int argc, _TCHAR* argv[])
{
    //界说了三个short option, 范例为 ARG_REQUIRED
    ACE_Get_Opt opt(argc, argv, "s:u:p:", 1, 0);
    //界说三个long option, 并与相应的short option 举办关联
    if(opt.long_option("server", 's', ACE_Get_Opt::ARG_REQUIRED) == -1)
    {
        cout << "server option can not be added" << endl;
    }
    if(opt.long_option("user", 'u', ACE_Get_Opt::ARG_REQUIRED) == -1)
    {
        cout << "user option can not be added" << endl;
    }
    if(opt.long_option("pwd", 'p', ACE_Get_Opt::ARG_REQUIRED) == -1)
    {
        cout << "pwd option can not be added" << endl;
    }
    
    //开始理会
    for(int arg = 0; (arg = opt()) != -1;)
    {
        switch (arg)
        {
        case 's':
            cout << "server is " << opt.opt_arg() << endl;
            break;
        case 'u':
            cout << "user is " << opt.opt_arg() << endl;
            break;
        case 'p':
            cout << "pwd is " << opt.opt_arg() << endl;
            break;
        //理会 long option
        case 0:
            if(_stricmp(opt.long_option(), "server") == 0)
            {
                cout << "long option server is" << opt.opt_arg() << endl;
            }
            break;
        default:
            break;
        }
    }
    //假如直接运行,可能利用方法差池,则显示辅佐
    if(opt.opt_ind() + 2 < argc)
    {
        cout << "the usage is : GetOptTest.exe [option]" << endl;
        cout << "\t [-s] server address" << endl;
        cout << "\t [-u] user name" << endl;
        cout << "\t [-p] password of user" << endl
        << endl;
    }
    return 0;
}

呼吁行理会实战

至此呼吁行理会的根基成果已经都先容了,并且相应的代码已经完成,那么就让我们来浏览一下理会的结果吧。

详细的呼吁行

-s 127.0.0.1 --server 192.168.0.1 -u hbccdf -p pwdfortest

运行结果图

如何操作ACE_Get_Opt剖析号令行

#p#分页标题#e#

其实成果很简朴,ACE_Get_Opt的利用也很简朴,可是一点点进修,并举办总结,是我一直需要提高的处所。今后会僵持把学到的对象举办总结,并分享到博客上。

作者:cnblogs 缘生梦

    关键字:

在线提交作业