2011-03-15

Simple command line parser


class CCmdLine
{
   CString cmd;
public:
   CCmdLine(const CString& cmdline) : cmd(cmdline)
   { }

   template <typename T>
   T value(const CString& name, const T& def = T())
   {
    CString para;
    para.Format(_T("-(%s)(\\b+)"), name);
    CAtlRegExp<> parser;
    CAtlREMatchContext<> match;
    // search for a "-parameter" followed by a quoted or unquoted string not starting with "-"
    if ((parser.Parse(para + _T("{(!-)(\\q)|([^ \t]+)}")) != REPARSE_ERROR_OK)
    || (!parser.Match(cmd, &match))
    || (match.m_uNumGroups < 1))
        return def;                // Unexpected error, return default value

    const CAtlREMatchContext<>::RECHAR *start = 0, *end = 0;
    match.GetMatch(0, &start, &end);
    ptrdiff_t len = end - start;
    if (len <= 0)
        return def;
    CString val(start, (int)len);
    val.Trim(_T("\'\""));            // remove quotes
    return variant_t(val);          // convert the string value to T using COM VARIANT conversion
   }
};
. . . .
   
// program.exe -host mycoolhosting.org -port 8080 -file "C:\Users\Me\Documents\after party.jpg"
...
CCmdLine options(CA2W(lpszCmdLine);
  
CString host = options.value<CString>(L"host");
int port = options.value<int>(L"port", 8000);
CString file = options.value<CString>(L"file");

No comments:

Post a Comment