65.9K
CodeProject 正在变化。 阅读更多。
Home

CCmdLine - 一个命令行解析器

2001年6月20日

CPOL

1分钟阅读

viewsIcon

403365

downloadIcon

3975

一个简单的命令行解析类。

引言

使用标准的 C 字符串函数(strlen、strcpy 等)甚至 CString 操作符解析命令行是一个噩梦。但是,CCmdLine 使其变得毫不费力。

CCmdLine 最初是为控制台应用程序编写的,但可以轻松地在任何需要命令行解析的应用程序中使用。

CCmdLine 使用 STL 作为其集合类,因此它适用于 MFC 和非 MFC 应用程序。 如果在 MFC 应用程序中使用它,则开关和参数将作为 'CString' 返回。 如果在非 MFC 应用程序中使用它,则它们将作为 STL 'string' 返回。

CCmdLine 是一种将命令行解析为开关参数的简单方法。例如

MyApp.exe -sw1 arg1 arg2 -sw2 arg3 -sw3 -sw4

在使用 CCmdLine 时,“-sw1”、“-sw2”、“-sw3”和“-sw4”是开关,“arg1”、“arg2”和“arg3”是参数

示例

假设我们编写的应用程序使用具有两个必需开关和两个可选开关的命令行。 如果未提供必需的开关,应用程序应中止,如果未提供可选的开关,则继续使用默认值。

    示例命令行

    MyApp.exe -p1 text1 text2 -p2 "this is a big argument" -opt1 -55 -opt2

    开关 -p1 和 -p2 是必需的。

    p1 有两个参数,p2 有一个。

    开关 -opt1 和 -opt2 是可选的。

    opt1 需要一个数字参数。

    opt2 没有参数。

    此外,假设应用程序如果命令行中存在“-h”开关,则显示“帮助”屏幕。

示例

以下是如何使用 CCmdLine 处理命令行处理

// if this is an MFC app, un-comment the next line
// #include "stdafx.h"

#include "CmdLine.h"

void main(int argc, char **argv)
{
  // our cmd line parser object
  CCmdLine cmdLine;

  // parse the command line.
  // in MFC apps, use __argc and __argv here
  if (cmdLine.SplitLine(argc, argv) < 1)
  {
     // no switches were given on the command line, abort
     ASSERT(0);
     exit(-1);
  }

  // test for the 'help' case
  if (cmdLine.HasSwitch("-h"))
  {
     show_help();
     exit(0);
  }

  // StringType is defined in CmdLine.h.
  // it is CString when using MFC, else STL's 'string'
  StringType p1_1, p1_2, p2_1;

  // get the required arguments
  try
  {
     // if any of these GetArgument calls fail,
     // we'll end up in the catch() block

     // get the first -p1 argument (arg number '0')
     p1_1 = cmdLine.GetArgument("-p1", 0);

     // get the second -p1 argument (arg number '1')
     p1_2 = cmdLine.GetArgument("-p1", 1);

     // get the first -p2 argument
     p2_1 = cmdLine.GetArgument("-p2", 0);

  }
  catch (...)
  {
     // one of the required arguments was missing, abort
     ASSERT(0);
     exit(-1);
  }

  // get the optional parameters

  // the GetSafeArgument member does not throw exceptions, and
  // allows for the use of a default value, if the switch is not found.

  // get the argument, convert it to an int.
  // default to '100', if the argument was not found
  int iOpt1Val =    atoi( cmdLine.GetSafeArgument( "-opt1", 0, 100 ) );

  // since opt2 has no arguments, just test for the presence of
  // the '-opt2' switch
  bool bOptSwitch2 =   cmdLine.HasSwitch("-opt2");

  .... and so on....

}

非常简单...

历史

  • 2002年1月31日 - 更新源代码。
  • 2011年8月25日 - 更新源代码。
© . All rights reserved.