Click here to Skip to main content
Licence 
First Posted 17 Aug 2002
Views 144,543
Bookmarked 91 times

Command line parser

By | 17 Aug 2002 | Article
An intuitive and extensible command line parser class that handles multiple command line formats

Introduction

Getting list of arguments from command line is a common task which is required by a lot of applications. However, there is no standard solution (as far as I know ;). So I wrote class CCmdLineParser, which can parse arguments from command line, if they are typed in folowing form: 

  • /Key 
  • /KeyWithValue:Value 
  • /KeyWithComplexValue:"Some really complex value of /KeyWithComplexValue"

Of course, multiple keys, Unicode and long (up to 32Kb) command lines are supported.

This implementation requires the MFC or ATL CString class, or some clone with similar interface as well as the STL class map.

Usage

First, you should construct the object and call the Parse function (from constructor or
CCmdLineParser parser(::GetCommandLine());
or
CCmdLineParser parser;
parser.Parse(_T("/Key /Key2:Val /Key3:\"Complex-Value\" -Key4"));

Then, there are two ways of working with results. You can check if some particular key was specified in the command line:

if(parser.HasKey(_T("Key")) {
	// Do some stuff
}
if(parser.HasKey(_T("Key2")) {
	LPCTSTR szKey2Value = parser.GetVal(_T("Key2"));
	// Do something with value of Key2
}

LPCTSTR szKey3Value = parser.GetVal(_T("Key3"));
if(szKey3Value) {
	// There was key "Key3" in input,  
} else {
	// No key "Key3" in input
}

LPCTSTR szKey4Value = parser.GetVal(_T("Key4"));
// Key4 was found in input, but since no value was specified, 
// szKey4Value points to empty string

Another way to use is to enumerate all keys in command line:

CString sKey, sValue;

CCmdLineParser::POSITION pos = parser.getFirst();
while(!realParser.isLast(pos)) {
	realParser.getNext(pos, sKey, sValue);
	// Do something with current key and value
}

Customization and "how it works"

Repeated keys

If several different values are specified with same key, only the first value is stored. So, if user passes command line /Add:One /Add:Two, /Add:Two will be ignored and will not be added to parsed list.

Case sensitive/insensitive

By default, keys are not case-sensitive. So, /KeyOne is equal to -keyONE. This is done by converting all keys to lowercase before storing them. If you want to change this behaviour, call setCaseSensitive(true) or call the constructor with the second argument set to true:
CCmdLineParser parser(::GetCommandLine(), true);
This will switch the parser to case-sensitive mode, and if the user passes -key, then GetKey(_T("Key")) will return false

Syntax

Formally, command line should be in following form:
CommandLine::=[<Key> [,<Key>...]]
<Key>::=<Delimeter>KeyName[<Separator><Value>]
<Value> ::= { KeyValue | <QuoteChar>Quoted Key Value<QuoteChar>} ][
<Delimeter>::= { - | / }
<Separator>::= { : }
<QuoteChar>::= { " }

Values for <Delimeter>, <Separator> and <QuoteChar> are stored in static variables m_sDelimeters, m_sValueSep and m_sQuotes respectively. If you want to change them (for instance, allow user to specify quoted values in apostrophes), you can do it in the beginning of CmdLineParser.cpp:

const TCHAR CCmdLineParser::m_sQuotes[] = _T("\"\'");
Note: If you want to change m_sDelimeters, space must be the first character of this string. Also, if you have your own CString class with other name than CString, you can change it in the beginning of CmdLineParser.h:
typedef MyOwnCString CCmdLineParser_String;
That's it! ;)

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

About the Author

Pavel Antonov

Web Developer

Russian Federation Russian Federation

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionThis wheel has been reinvented a number of times: TCLAP, boost program_options to name a few PinmemberLarry S. Smith21:28 17 Dec '11  
GeneralMy vote of 4 Pinmemberhivhiv23:18 17 Dec '10  
QuestionGood!But a question. Pinmembersuxiaojack1:28 26 Apr '08  
GeneralBug report and my implementation of CCmdLineParser::CCmdLineParser() [modified] Pinmemberdoroboy21:11 27 Nov '07  
Good job! thanks very much.
But when the execute file is in one folder which include the Delimeter character "-", the Parse() function will take it as a key mistakenly. I think this is a bug.
And why don't you use the argc & argv? Below is my implementation of CCmdLineParser::CCmdLineParser(). I think this is simpler and easier to understand than yours.
const TCHAR CCmdLineParser::m_sDelimeters[] = _T("/");  // Can be _T("-/"),  for instance
const TCHAR CCmdLineParser::m_sValueSep[] = _T(":");    // Can be _T("=:"),  for instance. Space need NOT be in set.
//const TCHAR CCmdLineParser::m_sQuotes[] = _T("\"");   // No need any more! so I comment out this line.

CCmdLineParser::CCmdLineParser(int argc, TCHAR* argv[], bool bCaseSensitive) : m_bCaseSensitive(bCaseSensitive)
{
    const CString sEmpty;
    m_ValsMap.clear();
 
    for (int i=1; i<argc; i++) {
        LPCTSTR sArg = _tcspbrk(argv[i], m_sDelimeters);
        if ( (NULL == sArg) || (sArg != argv[i]) || ('\0' == sArg[1]) ) {  // The m_sDelimeters chacracter not found || The first character is not in m_sDelimeters set || cmdline ends with /
            continue;
        }
        
        sArg = _tcsinc(sArg);
        LPCTSTR sVal = _tcspbrk(sArg, m_sValueSep);
 
        if( NULL == sVal ) {          // cmdline ends with /Key
            CString csKey(sArg);
            if(!m_bCaseSensitive) {
                csKey.MakeLower();
            }
            m_ValsMap.insert(CValsMap::value_type(csKey, sEmpty));
        } else {                    // cmdline ends with /Key:*
            CString csKey(sArg, sVal - sArg);
            if(!csKey.IsEmpty()) {      // Prevent /: case
                if(!m_bCaseSensitive) {
                    csKey.MakeLower();
                }
                if ( 1 == _tcslen(sVal) ) {     // cmdline ends with /Key:
                    sVal = sEmpty;
                } else {                    // cmdline ends with /Key:Val
                    sVal = _tcsinc(sVal);
                }
                m_ValsMap.insert(CValsMap::value_type(csKey, sVal));
            }
        }
    }
}

GeneralRe: Bug report and my implementation of CCmdLineParser::CCmdLineParser() Pinmemberdoroboy13:56 13 Dec '07  
GeneralThank you, I'm just looking for this PinmemberPeter Liu3:46 26 Aug '07  
GeneralExcellent Pinmemberkpinkert9:06 19 Aug '05  
GeneralSupporting - - parameters and map. PinmemberdB.6:52 29 Jun '05  
GeneralRe: Supporting - - parameters and map. PinmemberdB.11:05 19 Dec '05  
GeneralToo much blah.... Pinmemberdouglash16:29 28 Oct '04  
GeneralRe: Too much blah.... PinmemberJohn M. Drescher6:53 28 Oct '04  
GeneralRe: Too much blah.... Pinmemberpeterchen1:28 1 Nov '04  
GeneralRe: Too much blah.... PinmemberTim Stubbs5:11 28 Nov '08  
GeneralAnother suggestion PinmemberJim Crafton3:46 3 Oct '04  
GeneralRe: Another suggestion Pinmemberahz2:33 14 Dec '05  
GeneralThanks PinmemberRutger Ellen4:50 23 Jul '04  
GeneralLicense issue... PinmemberR. Douglas Barbieri8:48 14 Apr '04  
GeneralLicense: Freeware PinmemberPavel Antonov20:25 14 Apr '04  
GeneralRe: License: Freeware PinmemberMember 163325013:21 28 Jul '10  
GeneralNot a standard Pinsusscodep@michaelleesimons.com9:35 13 Jan '04  
GeneralRe: Not a standard PinmemberStewart Heitmann18:41 19 Jan '04  
GeneralAt last !!! PinmemberSerge Wautier2:34 11 Dec '03  
Generalspaces in command line parameters PinmemberJogi011:17 17 Nov '03  
GeneralRe: spaces in command line parameters PinmemberPavel Antonov1:55 17 Nov '03  
GeneralRe: spaces in command line parameters PinmemberJogi010:59 19 Nov '03  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 18 Aug 2002
Article Copyright 2002 by Pavel Antonov
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid