Get_Opt.h

Go to the documentation of this file.
00001 // -*- C++ -*-
00002 
00003 //==========================================================================
00004 /**
00005  *  @file    Get_Opt.h
00006  *
00007  *  Get_Opt.h,v 4.46 2005/11/03 17:19:49 ossama Exp
00008  *
00009  *  @author Douglas C. Schmidt <schmidt@cs.wustl.edu>
00010  *  @author Don Hinton <dhinton@gmx.net> (added long option support)
00011  */
00012 //==========================================================================
00013 
00014 #ifndef ACE_GET_OPT_H
00015 #define ACE_GET_OPT_H
00016 #include /**/ "ace/pre.h"
00017 
00018 #include "ace/SStringfwd.h"
00019 #include "ace/Containers.h"
00020 
00021 #if !defined (ACE_LACKS_PRAGMA_ONCE)
00022 # pragma once
00023 #endif /* ACE_LACKS_PRAGMA_ONCE */
00024 
00025 #undef optind
00026 #undef optarg
00027 #undef opterr
00028 
00029 ACE_BEGIN_VERSIONED_NAMESPACE_DECL
00030 
00031 /*
00032  *  These definitions are for backward compatibility with previous versions.
00033  *  of ACE_Get_Opt.
00034  */
00035 
00036 /**
00037  * @class ACE_Get_Opt
00038  *
00039  * @brief Iterator for parsing command-line arguments.
00040  *
00041  * This is a C++ wrapper for getopt(3c) and getopt_long(3c).
00042  */
00043 
00044 class ACE_Export ACE_Get_Opt
00045 {
00046 public:
00047   /// Mutually exclusive ordering values.
00048   enum
00049   {
00050    /**
00051     * REQUIRE_ORDER means that processing stops and @c EOF is
00052     * returned as soon as a non-option argument is found. @c opt_ind()
00053     * will return the index of the next @a argv element so the program
00054     * can continue processing the rest of the @a argv elements.
00055     */
00056     REQUIRE_ORDER = 1,
00057 
00058    /**
00059     * PERMUTE_ARGS means the @a argv elements are reordered dynamically
00060     * (permuted) so that all options appear first. When the elements are
00061     * permuted, the order of the options and the following arguments are
00062     * maintained. When the last option has been processed, @c EOF is
00063     * returned and @c opt_ind() returns the index into the next non-option
00064     * element.
00065     */
00066     PERMUTE_ARGS = 2,
00067 
00068    /**
00069     * RETURN_IN_ORDER means each @a argv element is processed in the
00070     * order is it seen.  If the element is not recognized as an option, '1'
00071     * is returned and @c opt_arg() refers to the @a argv element found.
00072     */
00073     RETURN_IN_ORDER = 3
00074   };
00075 
00076   /// Mutually exclusive option argument mode used by long options.
00077   enum OPTION_ARG_MODE
00078   {
00079     /// Doesn't take an argument.
00080     NO_ARG = 0,
00081 
00082     /// Requires an argument, same as passing ":" after a short option
00083     /// character in @a optstring.
00084     ARG_REQUIRED = 1,
00085 
00086     /// Argument is optional, same as passing "::" after a short
00087     /// option character in @a optstring.
00088     ARG_OPTIONAL = 2
00089   };
00090 
00091   /**
00092    * Constructor initializes the command line to be parsed. All information
00093    * for parsing must be supplied to this constructor.
00094    *
00095    * @param argc          The number of @a argv elements to parse.
00096    * @param argv          Command line tokens, such as would be passed
00097    *                      to @c main().
00098    * @param optstring     Nul-terminated string containing the legitimate
00099    *                      short option characters.  A single colon ":"
00100    *                      following an option character means the option
00101    *                      requires an argument.  A double colon "::" following
00102    *                      an option character means the argument is optional.
00103    *                      The argument is taken from the rest of the current
00104    *                      @a argv element, or from the following @a argv
00105    *                      element (only valid for required arguments;
00106    *                      optional arguments must always reside in the same
00107    *                      @a argv element). The argument value, if any is
00108    *                      returned by the @c opt_arg() method.
00109    *                      @a optstring can be extended by adding long options
00110    *                      with corresponding short options via the
00111    *                      @c long_option() method.  If the short option
00112    *                      already appears in @a optstring, the argument
00113    *                      characteristics must match, otherwise it is added.
00114    *                      See @c long_option() for more information.
00115    *                      If 'W', followed by a semi-colon ';' appears in
00116    *                      @a optstring, then any time a 'W' appears on the
00117    *                      command line, the following argument is treated as
00118    *                      a long option.  For example, if the command line
00119    *                      contains "program -W foo", "foo" is treated as a
00120    *                      long option, that is, as if "program --foo" had
00121    *                      been passed.
00122    *                      The following characters can appear in @a optstring
00123    *                      before any option characters, with the described
00124    *                      effect:
00125    *                      - '+' changes the @a ordering to @a REQUIRE_ORDER.
00126    *                      - '-' changes the @a ordering to @a RETURN_IN_ORDER.
00127    *                      - ':' changes the return value from @c operator()
00128    *                            and get_opt() from '?' to ':' when an option
00129    *                            requires an argument but none is specified.
00130    *
00131    * @param skip_args     Optional (default 1). The specified number of
00132    *                      initial elements in @a argv are skipped before
00133    *                      parsing begins. Thus, the default prevents
00134    *                      @a argv[0] (usually the command name) from being
00135    *                      parsed. @a argc includes all @a argv elements,
00136    *                      including any skipped elements.
00137    * @param report_errors Optional, if non-zero then parsing errors cause
00138    *                      an error message to be displayed from the
00139    *                      @c operator() method before it returns. The
00140    *                      error message is suppressed if this argument is 0.
00141    *                      This setting also controls whether or not an error
00142    *                      message is displayed in @c long_option() encounters
00143    *                      an error.
00144    * @param ordering      Optional (default is @c PERMUTE_ARGS); determines
00145    *                      how the @a argv elements are processed. This argument
00146    *                      is overridden by two factors:
00147    *                      -# The @c POSIXLY_CORRECT environment variable. If
00148    *                         this environment variable is set, the ordering
00149    *                         is changed to @c REQUIRE_ORDER.
00150    *                      -# Leading characters in @a optstring (see above).
00151    *                         Any leading ordering characters override both
00152    *                         the @a ordering argument and any effect of the
00153    *                         @c POSIXLY_CORRECT environment variable.
00154    * @param long_only     Optional. If non-zero, then long options can be
00155    *                      specified using a single '-' on the command line.
00156    *                      If the token is not a long option, it is processed
00157    *                      as usual, that is, as a short option or set of
00158    *                      short options.
00159    *
00160    * Multiple short options can be combined as long as only the last
00161    * one can takes an argument. For example, if @a optstring is defined as
00162    * @c "abc:" or @c "abc::" then the command line @e "program -abcxxx" short
00163    * options @e a, @e b, and @e c are found with @e "xxx" as the argument for
00164    * @e c.
00165    * However, if the command line is specified as @e "program -acb" only
00166    * options @e a and @e c are found with @e "b" as the argument for @e c.
00167    * Also, for options with optional arguments, that is, those followed by
00168    * "::", the argument must be in the same @a argv element, so "program -abc
00169    * xxx" will only find "xxx" as the argument for @e c if @a optstring is
00170    * specified as @c "abc:" not @c "abc::".
00171    */
00172   ACE_Get_Opt (int argc,
00173                ACE_TCHAR **argv,
00174                const ACE_TCHAR *optstring = ACE_LIB_TEXT (""),
00175                int skip_args = 1,
00176                int report_errors = 0,
00177                int ordering = PERMUTE_ARGS,
00178                int long_only = 0);
00179 
00180   /// Default dtor.
00181   ~ACE_Get_Opt (void);
00182 
00183   /**
00184    * Scan elements of @a argv (whose length is @a argc) for short option
00185    * characters given in @a optstring or long options (with no short
00186    * option equivalents).
00187    *
00188    * If an element of @a argv starts with '-', and is not exactly "-"
00189    * or "--", then it is a short option element.  The characters of this
00190    * element (aside from the initial '-') are option characters. If
00191    * it starts with "--" followed by other characters it is treated as
00192    * a long option.  If @c operator() is called repeatedly, it returns
00193    * each of the option characters from each of the option elements.
00194    *
00195    * @return The parsed option character. The following characters have
00196    * special significance.
00197    * @retval 0      A long option was found
00198    * @retval '\?'   Either an unknown option character was found, or the
00199    *                option is known but requires an argument, none was
00200    *                specified, and @a optstring did not contain a leading
00201    *                colon.
00202    * @retval ':'    A known option character was found but it requires an
00203    *                argument and none was supplied, and the first character
00204    *                of @a optstring was a colon. @c opt_opt() indicates
00205    *                which option was specified.
00206    * @retval '1'    @c RETURN_IN_ORDER was specified and a non-option argument
00207    *                was found.
00208    * @retval EOF No more option characters were found.  @c opt_ind() will
00209    *             return the index in @a argv of the first @a argv element
00210    *             that is not an option.  If @c PERMUTE_ARGS was
00211    *             specified, the @a argv elements have been permuted so that
00212    *             those that are not options now come last.
00213    *
00214    * @note The standards are unclear with respect to the conditions under
00215    * which '?' and ':' are returned, so we scan the initial characters of
00216    * @a optstring up unto the first short option character for '+', '-',
00217    * and ':' in order to determine ordering and missing argument behavior.
00218    */
00219   int operator () (void);
00220 
00221   /**
00222    * For communication from @c operator() to the caller.  When
00223    * @c operator() finds an option that takes an argument, the argument
00224    * value is returned from this method, otherwise it returns 0.
00225    */
00226   ACE_TCHAR *opt_arg (void) const;
00227 
00228   /**
00229    * Returns the most recently matched option character. Especially
00230    * useful when operator() returns ':' for an unspecified argument
00231    * that's required, since this allows the caller to learn what option
00232    * was specified without its required argument.
00233    */
00234   int opt_opt (void);
00235 
00236   /**
00237    * Index in @a argv of the next element to be scanned.  This is used
00238    * for communication to and from the caller and for communication
00239    * between successive calls to @c operator().  On entry to
00240    * @c operator(), zero means this is the first call; initialize.
00241    *
00242    * When @c operator() returns @c EOF, this is the index of the first of
00243    * the non-option elements that the caller should itself scan.
00244    *
00245    * Otherwise, @c opt_ind() communicates from one call to the next how
00246    * much of @a argv has been scanned so far.
00247    */
00248   int &opt_ind (void);
00249 
00250   /// Adds a long option with no corresponding short option.
00251   /**
00252    * If the @a name option is seen, @c operator() returns 0.
00253    *
00254    * @param name          The long option to add.
00255    * @param has_arg       Defines the argument requirements for
00256    *                      the new option.
00257    *
00258    * @retval 0  Success
00259    * @retval -1 The long option can not be added.
00260    */
00261   int long_option (const ACE_TCHAR *name,
00262                    OPTION_ARG_MODE has_arg = NO_ARG);
00263 
00264   /// Adds a long option with a corresponding short option.
00265   /**
00266    * @param name          The long option to add.
00267    * @param short_option  A character, the short option that corresponds
00268    *                      to @a name.
00269    * @param has_arg       Defines the argument requirements for
00270    *                      the new option.  If the short option has already
00271    *                      been supplied in the @a optstring, @a has_arg
00272    *                      must match or an error is returned; otherwise, the
00273    *                      new short option is added to the @a optstring.
00274    *
00275    * @retval 0  Success
00276    * @retval -1 The long option can not be added.
00277    */
00278   int long_option (const ACE_TCHAR *name,
00279                    int short_option,
00280                    OPTION_ARG_MODE has_arg = NO_ARG);
00281 
00282   /// Returns the name of the long option found on the last call to
00283   /// @c operator() or 0 if none was found.
00284   const ACE_TCHAR *long_option (void) const;
00285 
00286   /// The number of arguments in the internal @c argv_.
00287   int argc (void) const;
00288 
00289   /// Accessor for the internal @c argv_ pointer.
00290   ACE_TCHAR **argv (void) const;
00291 
00292   /// Accessor for the @c last_option that was processed.  This allows
00293   /// applications to know if the found option was a short or long
00294   /// option, and is especially useful in cases where it was invalid
00295   /// and the caller wants to print out the invalid value.
00296   const ACE_TCHAR *last_option (void) const;
00297 
00298   /// Dump the state of an object.
00299   void dump (void) const;
00300 
00301   /// Return the @a optstring.  This is handy to verify that calls to
00302   /// long_option added short options as expected.
00303   const ACE_TCHAR *optstring (void) const;
00304 
00305 public:
00306   /*
00307    * The following five data members should be private, but that
00308    * would break backwards compatibility.  However, we recommend not
00309    * writing code that uses these fields directly.
00310    */
00311 
00312   /// Holds the @a argc count.
00313   /**
00314    * @deprecated This is public for backwards compatibility only.
00315    * It will be made private in a release of ACE past 5.3.  Do not
00316    * write code that relies on this member being public; use the
00317    * @c argc() accessor method instead.
00318    */
00319   int argc_;
00320 
00321   /// Holds the @a argv pointer.
00322   /**
00323    * @deprecated This is public for backwards compatibility only.
00324    * It will be made private in a release of ACE past 5.3.  Do not
00325    * write code that relies on this member being public; use the
00326    * @c argv() accessor method instead.
00327    */
00328   ACE_TCHAR **argv_;
00329 
00330   /// Index in @c argv_ of the next element to be scanned.
00331   /**
00332    * @deprecated This is public for backwards compatibility only.
00333    * It will be made private in a release of ACE past 5.3.  Do not
00334    * write code that relies on this member being public; use the
00335    * @c opt_ind() accessor method instead.
00336    */
00337   int optind;
00338 
00339   /// Callers store zero here to inhibit the error message for
00340   /// unrecognized options.
00341   /**
00342    * @deprecated This is public for backwards compatibility only.
00343    * It will be made private in a release of ACE past 5.3.  Do not
00344    * write code that relies on this member being public; use the
00345    * @a report_errors argument to this class's constructor instead.
00346    */
00347   int opterr;
00348 
00349   /// Points to the option argument when one is found on last call to
00350   /// @c operator().
00351   /**
00352    * @deprecated This is public for backwards compatibility only.
00353    * It will be made private in a release of ACE past 5.3.  Do not
00354    * write code that relies on this member being public; use the
00355    * @c opt_arg() accessor method instead.
00356    */
00357   ACE_TCHAR *optarg;
00358 
00359 private:
00360   /**
00361    * @class ACE_Get_Opt_Long_Option  This class is for internal use
00362    * in the ACE_Get_Opt class, and is inaccessible to users.
00363    */
00364   class ACE_Get_Opt_Long_Option
00365   {
00366   public:
00367     /// ctor
00368     ACE_Get_Opt_Long_Option (const ACE_TCHAR *name,
00369                              int has_arg,
00370                              int val = 0);
00371 
00372     /// Dtor.
00373     ~ACE_Get_Opt_Long_Option (void);
00374 
00375     bool operator < (const ACE_Get_Opt_Long_Option &rhs);
00376 
00377     /// Long option name.
00378     const ACE_TCHAR *name_;
00379 
00380     /// Contains value for <OPTION_ARG_MODE>.
00381     int has_arg_;
00382 
00383     /// Contains a valid short option character or zero if it doesn't
00384     /// have a corresponding short option.  It can also contain a
00385     /// non-printable value that cannot be passed to <optstring> but
00386     /// will be returned by <operator()>.  This is handy for
00387     /// simplifying long option handling, see tests/Get_Opt_Test.cpp
00388     /// for an example of this technique.
00389     int val_;
00390   };
00391 
00392   /// Updates nextchar_.
00393   int nextchar_i (void);
00394 
00395   /// Handles long options.
00396   int long_option_i (void);
00397 
00398   /// Handles short options.
00399   int short_option_i (void);
00400 
00401   /// If permuting args, this functions manages the nonopt_start_ and
00402   /// nonopt_end_ indexes and makes calls to permute to actually
00403   /// reorder the <argv>-elements.
00404   void permute_args (void);
00405 
00406   /// Handles reordering <argv>-elements.
00407   int permute (void);
00408 
00409   /// Set last_option.
00410   void last_option (const ACE_TString &s);
00411 
00412   // Disallow copying and assignment.
00413   ACE_Get_Opt (const ACE_Get_Opt &);
00414   ACE_Get_Opt &operator= (const ACE_Get_Opt &);
00415 
00416 private:
00417 
00418   /// Holds the option string.
00419   ACE_TString *optstring_;
00420 
00421   /// Treat all options as long options.
00422   int long_only_;
00423 
00424   /// Keeps track of whether or not a colon was passed in <optstring>.
00425   /// This is used to determine the return value when required
00426   /// arguments are missing.
00427   int has_colon_;
00428 
00429   /// This is the last option, short or long, that was processed.  This
00430   /// is handy to have in cases where the option passed was invalid.
00431   ACE_TString *last_option_;
00432 
00433   /**
00434    * The next char to be scanned in the option-element in which the
00435    * last option character we returned was found.  This allows us to
00436    * pick up the scan where we left off   *
00437    * If this is zero, or a null string, it means resume the scan
00438    * by advancing to the next <argv>-element.
00439    */
00440   ACE_TCHAR *nextchar_;
00441 
00442   /// Most recently matched short option character.
00443   int optopt_;
00444 
00445   /// Keeps track of ordering mode (default <PERMUTE_ARGS>).
00446   int ordering_;
00447 
00448   /// Index of the first non-option <argv>-element found (only valid
00449   /// when permuting).
00450   int nonopt_start_;
00451 
00452   /// Index of the <argv>-element following the last non-option element
00453   /// (only valid when permuting).
00454   int nonopt_end_;
00455 
00456   /// Points to the long_option found on last call to <operator()>.
00457   ACE_Get_Opt_Long_Option *long_option_;
00458 
00459   /// Array of long options.
00460   ACE_Array<ACE_Get_Opt_Long_Option*> long_opts_;
00461 
00462   /// Declare the dynamic allocation hooks.
00463   ACE_ALLOC_HOOK_DECLARE;
00464 
00465 };
00466 
00467 ACE_END_VERSIONED_NAMESPACE_DECL
00468 
00469 #if defined (__ACE_INLINE__)
00470 #include "ace/Get_Opt.inl"
00471 #endif /* __ACE_INLINE__ */
00472 
00473 #include /**/ "ace/post.h"
00474 #endif /* ACE_GET_OPT_H */

Generated on Thu Nov 9 09:41:51 2006 for ACE by doxygen 1.3.6