Cross-Platform C++

ot::auxil
class CommandLineParser

#include "ot/auxil/CommandLineParser.h"

A POSIX-compliant command line parser. C/C++ programs normally receive the command line from the operating system's shell as an array of null-delimited strings passed in the argv argument to the main() function. The passed array of command tokens comprises the name of the executable, option flags and file names or other positional parameters. The following is a typical command line which needs to be interpreted (or parsed) by the receiving program:-
    $ xmlvalid -vc --summary test1.xml test2.xml

This class implements a command line parsing engine which recognises the rich command line syntax specified for POSIX commands (see below). An object-oriented approach is adopted, where each permissible option supported by the application is represented by an object that implements the CommandLineOption interface.

Most of the POSIX command parsing logic is implemented by this class, but the task of recognising individual option names as well as remembering if and how an option has been specified is delegated to an application-supplied set of objects that implement the CommandLineOption interface. OpenTop provides several concrete implementatons of CommandLineOption which cover most of the common (and not so common) command option types.

Applications typically use this class by first creating an instance on the stack and then registering one of more CommandLineOption objects. The parse() method is then called, passing in the argv parameter from function main(). Here is a typical example:-


    int main(int argc, char* argv[])
    {
        MemCheckSystemMonitor monitor;

        // Set up a command line parser to recognise our following options:
        // -h takes no argument
        // -p takes a mandatory argument
        // -r is a bool, which takes no argument and defaults to false
        BasicOption optHelp(OT_T("help"), 'h', BasicOption::none);
        BasicOption optPort(OT_T("port"), 'p', BasicOption::mandatory);
        BooleanOption optReply(OT_T("reply"), 'r', false);

        CommandLineParser cmdlineParser;
        cmdlineParser.addOption(&optHelp);
        cmdlineParser.addOption(&optPort);
        cmdlineParser.addOption(&optReply);

        // ...parse the command line, placing the command options
        // into their respective objects.
        try
        {
            cmdlineParser.parse(argc, argv);
        }
        catch (CommandLineException& e)
        {
            cerr << cmdlineParser.getProgramName() << ": " << e.getMessage() << endl << endl;
            return (1);
        }

        // If the user has request help, then provide some
        if(optHelp.isPresent())
        {
            showUsage();
            return (0);
        }
        // and now do something really useful...
    }


Command line syntax

A UNIX/DOS command line typically follows the following convention:-
	program-name [OPTION FLAG(S)...] [FILE(S)...]

Broadly speaking there are two ways of specifying command line options: using either the long or the short method. Long options start with a sequence of two dashes -- followed by the option name. Short options start with a single dash - (or alternatively a forward slash / in Microsoft Windows environments).

Long option names may be abreviated on the command line provided the abreviated name is unambiguous. For example, the long option named 'port' may be expressed as --port or --p so long as there aren't any other long option names beginning with p.

Short option names obviously cannot be abreviated, but they may be concatenated. For example, if a command accepts both an x and a y option, they may be expressed together as -x -y or, more succinctly, as -xy. The exception to this is when the option takes an argument. When a short option takes an argument, the text immediately following the option is taken as the argument. The argument may be concatenated with the short option or separated by white space (e.g. one or more spaces or tab characters).

Long options may also take arguments, but the difference here is that the argument must be separated from the option name by white space.




Constructor/Destructor Summary
CommandLineParser()
         Constructs a CommandLineParser.

Method Summary
 void addOption(CommandLineOption* pOption)
         Adds a CommandLineOption to the list of options which will be recognised during a parse() operation.
 StringList getFilenames(int argc, char* argv, int firstArg, int lastArg)
         Returns a list of filenames passed as command line argument(s) to the currently running program.
 unsigned getFirstPositionalArg() const
         Following a successful parse, return the index of the argument that represents the first non-option (i.e.
protected  CommandLineOption& getLongOption(const String& option, CommandLineOption::ArgumentType& ) const
         Locates a CommandLineOption that answers to the long option passed.
 const String& getProgramName() const
         Returns the program name, which is determined from the first argument passed to the parse() method.
protected  CommandLineOption& getShortOption(char option, CommandLineOption::ArgumentType& ) const
         Locates a CommandLineOption that answers to the short option passed.
 unsigned parse(int argc, char* argv)
         Parses the passed command line parameters, extracting any option names and associated arguments.

Typedefs

StringList

typedef std::list< String > StringList

Constructor/Destructor Detail

CommandLineParser

 CommandLineParser()
Constructs a CommandLineParser.


Method Detail

addOption

void addOption(CommandLineOption* pOption)
Adds a CommandLineOption to the list of options which will be recognised during a parse() operation.

Parameters:
pOption - a pointer to a CommandLineOption object. The pointer is stored and dereferenced during a parse() operation. For historical reasons, CommandLineOption is not a ManagedObject and does not support reference counting. For this reason, the application is responsible for maintaining the lifetime of the passed object. It must not be destroyed until after the last time parse() is called.

getFilenames

StringList getFilenames(int argc,
                        char* argv,
                        int firstArg,
                        int lastArg)
Returns a list of filenames passed as command line argument(s) to the currently running program. This is a useful function for making command line programs apparently behave the same way on Windows as they do when running under a UNIX shell.

The UNIX shell is more powerful than the Windows command prompt. One of the advanced functions it performs automatically is filename wildcard expansion (also known as filename 'globbing'). This feature allows users to enter a command like the following,

    dir *
...with the UNIX shell expanding the wildcard '*' into a list of all the files in the working directory.

When running under Windows this function performs filename globbing so that the command can be used from either a DOS/Windows or UNIX shell using the same syntax.

Under UNIX this is a very simple wrapper. Under Win32, each positional argument is tested for wildcard characters and expanded into a list of matching filenames.


getFirstPositionalArg

unsigned getFirstPositionalArg() const
Following a successful parse, return the index of the argument that represents the first non-option (i.e. positional) argument. For many programs, this will be the first filename arguement,


getLongOption

protected CommandLineOptiongetLongOption(const String& option,
                                           CommandLineOption::ArgumentType& ) const
Locates a CommandLineOption that answers to the long option passed.

Returns:
The requested CommandLineOption object.
Exceptions:
CommandLineException - if the option is unrecognized or ambiguous.

getProgramName

const StringgetProgramName() const
Returns the program name, which is determined from the first argument passed to the parse() method.


getShortOption

protected CommandLineOptiongetShortOption(char option,
                                            CommandLineOption::ArgumentType& ) const
Locates a CommandLineOption that answers to the short option passed.

Returns:
The requested CommandLineOption object.
Exceptions:
CommandLineException - if the option is unrecognized or ambiguous.

parse

unsigned parse(int argc,
               char* argv)
Parses the passed command line parameters, extracting any option names and associated arguments. Parsing is conducted according to POSIX rules. Short option names (defined as a single character) are recognized when prefixed by the short option prefix '-' ('/' is also recognized on Windows platforms).

Parsing stops as soon as a non-option argument is found.

Parameters:
argc - the number of array items in the argv parameter.
argv - an array of null-terminated strings containing the tokens specified on the command line..
Returns:
the index of the first non-option argument
Exceptions:
CommandLineException - if an invalid option has been specified on the command line


Cross-Platform C++

Found a bug or missing feature? Please email us at support@elcel.com

Copyright © 2000-2005 ElCel Technology   Trademark Acknowledgements