MLIB
Loading...
Searching...
No Matches
mlib::OptParser Class Reference

Command Line Parsing class. More...

Public Member Functions

 OptParser ()
 Initialize parser.
 
 OptParser (std::vector< const char * > &list)
 Initializes parser and sets the list of valid options.
 
 OptParser (std::initializer_list< const char * > list)
 Initializes parser and sets the list of valid options.
 
 OptParser (const char **list)
 Initializes parser and sets the list of options descriptors.
 
void set_options (std::vector< const char * > &list)
 Set list of valid options.
 
void add_option (const char *descr)
 Add a new option descriptor to the list of options.
 
int parse (int argc, const char *const *argv, int *stop=0)
 Parse a command line.
 
const std::string synopsis () const
 Return a nicely formatted syntax string containing all the options.
 
const std::string description (size_t indent_size=2) const
 Return options description.
 
const std::string & appname () const
 Return program name.
 
bool next (std::string &opt, std::string &optarg, char sep='|')
 
bool next (std::string &opt, std::vector< std::string > &optarg)
 Return next option in command line.
 
int getopt (const std::string &option, std::string &optarg, char sep='|') const
 
int getopt (const std::string &option, std::vector< std::string > &optarg) const
 Return a specific option from the command line.
 
int getopt (char option, std::string &optarg, char sep='|') const
 Return a specific option from the command line.
 
int getopt (char option, std::vector< std::string > &optarg) const
 Return a specific option from the command line.
 
bool hasopt (const std::string &option) const
 
bool hasopt (char option) const
 Check if command line has an option.
 

Detailed Description

Command Line Parsing class.

The parser matches approximately the POSIX specifications from: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html and GNU Standard for Command line Interface at http://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html

It accepts either short options composed of a dash (-) followed by a letter, or long options composed of -- followed by the option name. An option can have arguments that are either required or optional. If an option can have multiple arguments, all program arguments following the option are considered option arguments until the next option argument (argument preceded by - or --) or until the last argument. The first -- argument stops options' processing. All remaining arguments are considered non-option arguments (operands).

It is possible to specify several short options after one -, as long as all (except possibly the last) do not have required or optional arguments.

An option can be repeated. In this case, if the option has arguments, they are concatenated. For instance, the following two command lines are equivalent:

-d arg1 arg2 -e

and

-d arg1 -e -d arg2

Usage Instructions

  1. Construct an options parsing object with its list of valid options. See below for the syntax of an option descriptor.
  2. Call the OptParser::parse() function to process the command line arguments.
  3. Call OptParser::getopt() function to retrieve the status of the various options

See OptParser::add_option() function for the syntax of the option descriptor.

Example

The following example shows how to use an OptParser object and the different formats available for options.

const char *optlist[] {
"h|help", // option -h or --help
"a? optional_arg", // option -a can have an argument
// example: -a 1 or -a xyz
"b: required_arg", // option -b must be followed by an argument
// example: -b mmm
"c+ one_or_more_args", // option -c can be followed by one or more arguments
// example: -c 12 ab cd.
// The arguments finish at the next option
"d* 0_or_more_args", // option -d can have zero or more arguments
"e|", // option -e doesn't have any arguments
"f?longorshort optional", // option -f can be also written as --longorshort
// and can have an argument
":longopt required", // option --longopt must have an argument
0 };
OptParser optparser (optlist);
//sample command line
const char *samp_argv[]{ "program", "-a", "1", "-e", "--longopt", "par" };
optparser.parse (6, samp_argv);
string lo;
if (optparser.getopt ("longopt", lo))
{
// lo should be "par"
}
if (optparser.hasopt ('e'))
{
// option -e is present
}
Command Line Parsing class.
Definition options.h:34

Constructor & Destructor Documentation

◆ OptParser() [1/3]

mlib::OptParser::OptParser ( std::vector< const char * > &  list)

Initializes parser and sets the list of valid options.

Parameters
listarray of option descriptor strings
See also
OptParser::add_option for syntax of a descriptor string

◆ OptParser() [2/3]

mlib::OptParser::OptParser ( std::initializer_list< const char * >  list)

Initializes parser and sets the list of valid options.

Parameters
listarray of option descriptor strings
See also
OptParser::add_option for syntax of a descriptor string

◆ OptParser() [3/3]

mlib::OptParser::OptParser ( const char **  list)

Initializes parser and sets the list of options descriptors.

Parameters
listarray of pointers to option descriptor strings
Note
The list must be terminated with a null pointer.
See also
OptParser::add_option for syntax of a descriptor string

Member Function Documentation

◆ add_option()

void mlib::OptParser::add_option ( const char *  descr)

Add a new option descriptor to the list of options.

Parameters
descroption descriptor string

The descriptor string is has the following syntax:

[<short_form>] <flag> [<long_form>] [<spaces><arg_description>][\t<opt_description>]

<short_form> is a letter giving the short form of the option.

flag is one of:

  • ? option has one optional parameter
  • : option requires one argument
  • + option has one or more arguments
  • * option has 0 or more arguments
  • | option doesn't have any arguments

<long_form> is the long form of the option.

The <arg_description> is the argument description and is used to generate the synopsis string. The <opt_description> is the option description and is used to generate the description string. The <opt_description> part is preceded by a TAB (\t) character

Example:

"l?list list_arg \t list something"

The option syntax part is l?list, the argument description is list_arg and the option description is list something. The option can appear on the command line as:

-l stuff

or

--list stuff

or, simply:

-l

because the argument is optional.

The synopsis string will include the fragment:

-l|--list [list_arg]

and the description string will include the line:

-l|--list [list_arg] list something

◆ appname()

const std::string & mlib::OptParser::appname ( ) const
inline

Return program name.

This is the content of argv[0] without any path or extension.

◆ description()

const std::string mlib::OptParser::description ( size_t  indent_size = 2) const

Return options description.

Parameters
indent_sizenumber of spaces to indent each option description line

Each option and its synopsis is shown on a separate line indented by indent_size spaces, followed by the option description (if any).

◆ getopt() [1/3]

int mlib::OptParser::getopt ( char  option,
std::vector< std::string > &  optarg 
) const
inline

Return a specific option from the command line.

Parameters
optionthe requested option
optargoption argument(s)
Returns
number of occurrences on command line

◆ getopt() [2/3]

int mlib::OptParser::getopt ( const std::string &  option,
std::string &  optarg,
char  sep = '|' 
) const

Return a specific option from the command line

Parameters
optionthe requested option
optargoption argument(s)
sepseparator character to insert between arguments if option has multiple arguments
Returns
number of occurrences on command line

If the option has multiple arguments, optarg contains the arguments separated by separator character.

◆ getopt() [3/3]

int mlib::OptParser::getopt ( const std::string &  option,
std::vector< std::string > &  optarg 
) const
inline

Return a specific option from the command line.

Parameters
optionthe requested option
optargoption argument(s)
Returns
number of occurrences on command line

◆ hasopt() [1/2]

bool mlib::OptParser::hasopt ( char  option) const
inline

Check if command line has an option.

Parameters
optionshort form of the option

◆ hasopt() [2/2]

bool mlib::OptParser::hasopt ( const std::string &  option) const
inline

Check if command line has an option

Parameters
optionlong or short form of the option

◆ next() [1/2]

bool mlib::OptParser::next ( std::string &  opt,
std::string &  optarg,
char  sep = '|' 
)

Return next option in command line

Parameters
optoption
optargoption argument(s)
sepseparator character to insert between arguments if option has multiple arguments
Returns
true if successful, false if there are no more options

The internal position counter is initialized to the first option when command line is parsed and is incremented after each call to this function. Note that the internal counter is not thread-safe. Calls to next() function from any thread increment the same counter.

If the next option has both a long form and a short form, the function returns the long form.

If the option has multiple arguments, optarg contains the arguments separated by separator character.

◆ next() [2/2]

bool mlib::OptParser::next ( std::string &  opt,
std::vector< std::string > &  optarg 
)

Return next option in command line.

Parameters
optoption
optargoption argument(s)
Returns
true if successful, false if there are no more options

The internal position counter is initialized to the first option when command line is parsed and is incremented after each call to next() function. Note that the internal counter is not thread-safe. Calls to next() function from any thread increment the same counter.

If the next option has both a long form and a short form, the function returns the long form.

◆ parse()

int mlib::OptParser::parse ( int  argc,
const char *const *  argv,
int *  stop = 0 
)

Parse a command line.

Parameters
argcnumber of arguments
argvarray of arguments
stoppointer to an integer that receives the index of the first non-option argument if function is successful, or the index of the invalid option in case of failure
Returns
0 success
1 unknown option found
2 required argument is missing
3 invalid multiple options string

◆ set_options()

void mlib::OptParser::set_options ( std::vector< const char * > &  list)

Set list of valid options.

Parameters
list- array of option descriptor strings

Each valid option is described by a string in the list array.


The documentation for this class was generated from the following files: