Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simple command line processing

0.00/5 (No votes)
14 Jan 2002 1  
A simple method of parsing command line arguments; similar to getopt

Introduction

I wanted a simple method to parse command line parameters that would compile on both Windows and Unix. I was familiar with getopt but I couldn't find a compilable version of it in a standalone version, so I decided to make a simple version of it myself.

The result is something that is something that uses the getopt format specification but isn't getopt. It is basic but that is what I wanted - something quick to learn, use and debug. This is the result.

Features

  • Accepts getopt command line specification
  • Simple
  • Platform independent
  • Case dependent or independent matching

Limitations

  • It isn't getopt
  • All options on the command line must use flags. i.e. "program [-o] input_file" won't work, use "program [-o] -i input_file" instead

Notes

  • Uses exceptions
  • If using case-insensitive option matching, ensure that the string passed through as a_pszOptions is all lowercase

Example Usage

try
{
    CSimpleOptions cl( argc, argv, "Oa:" );
    while ( cl.next() )
    {
        switch ( cl.option() )
        {
        case 'O':
            bOption = true;
            break;
        case 'a':
            strArgument = cl.arg();
        }
    }
}
catch ( const SIMPLE_OPTIONS_EXCEPTION & e )
{
    fprintf( stderr, "Invalid argument: %s\n", e.what() );
    return 1;
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here