Introduction
Parsing command lines with the standard C string functions (strlen, strcpy, etc.) or even with the CString operators is a nightmare. But, CCmdLine makes it effortless.
CCmdLine was written for use with console apps, but can be easily used in any application which requires command-line parsing.
CCmdLine uses STL for its collection classes, so it works in both MFC and non-MFC apps. If you are using this in an MFC app, the switches and arguments will be returned as 'CString's. If you are using this in a non-MFC app, they will be returned as STL 'string's.
CCmdLine is a simple way to parse a command line into switches and arguments. Example :
MyApp.exe -sw1 arg1 arg2 -sw2 arg3 -sw3 -sw4
When using CCmdLine, "-sw1", "-sw2", "-sw3" and "-sw4" are switches and "arg1", "arg2" and "arg3" are arguments.
Example:
Assume the application we're writing uses a command line that has two required switches and two optional switches. The app should abort if the required switches are not present and continue with default values if the optional switches are not present.
MyApp.exe -p1 text1 text2 -p2 "this is a big argument" -opt1 -55 -opt2
Switches -p1 and -p2 are required.
p1 has two arguments and p2 has one.
Switches -opt1 and -opt2 are optional.
opt1 requires a numeric argument.
opt2 has no arguments.
Also, assume that the app displays a 'help' screen if the '-h' switch is present on the command line.
Example
Here's how you can use CCmdLine to handle the command line processing:
#include "CmdLine.h"
void main(int argc, char **argv)
{
CCmdLine cmdLine;
if (cmdLine.SplitLine(argc, argv) < 1)
{
ASSERT(0);
exit(-1);
}
if (cmdLine.HasSwitch("-h"))
{
show_help();
exit(0);
}
StringType p1_1, p1_2, p2_1;
try
{
p1_1 = cmdLine.GetArgument("-p1", 0);
p1_2 = cmdLine.GetArgument("-p1", 1);
p2_1 = cmdLine.GetArgument("-p2", 0);
}
catch (...)
{
ASSERT(0);
exit(-1);
}
int iOpt1Val = atoi( cmdLine.GetSafeArgument( "-opt1", 0, 100 ) );
bool bOptSwitch2 = cmdLine.HasSwitch("-opt2");
.... and so on....
}
Pretty simple stuff...
History
- 31 Jan 2002 - Updated source.
- 25 Aug 2011 - Updated source.