cmd_line_parser.h

Go to the documentation of this file.
00001 00004 /* 00005 * Copyright © 2002 Mikael Lindgren 00006 * 00007 * This material is provided "as is", with absolutely no warranty 00008 * expressed or implied. Any use is at your own risk. Permission to 00009 * use or copy this software for any purpose is hereby granted without 00010 * fee, provided the above notices are retained on all copies. 00011 * Permission to modify the code and to distribute modified code is 00012 * granted, provided the above notices are retained, and a notice that 00013 * the code was modified is included with the above copyright notice. 00014 * 00015 * This header is part of comet. 00016 * http://www.lambdasoft.dk/comet 00017 */ 00018 00019 #ifndef COMET_COMMAND_LINE_PARSER_H 00020 #define COMET_COMMAND_LINE_PARSER_H 00021 00022 #include <comet/tstring.h> 00023 00024 namespace comet { 00025 00029 class cmd_line_parser 00030 { 00031 public: 00032 enum kind_t { 00033 Name, // Name type token, has no leading / or - 00034 Option, // Option type token. Leading / or - skipped by token 00035 Value, // Value for name or option. Leading : or = skipped by token 00036 Done // No more tokens 00037 }; 00038 00039 explicit cmd_line_parser(const TCHAR* cmd_line): cmd_line_(cmd_line) 00040 { 00041 reset(); 00042 } 00043 00044 kind_t get_next_token(tstring& result) 00045 { 00046 static const TCHAR terminators[] = _T("=/- \t"); 00047 static const TCHAR white_space[] = _T(" \t"); 00048 00049 kind_t kind; 00050 00051 token_ = next_token_ + _tcsspn(next_token_, white_space); // Skip leading whitespace 00052 switch (*token_) 00053 { 00054 case 0: 00055 return Done; 00056 case _T('-'): 00057 case _T('/'): 00058 kind = Option; 00059 ++token_; 00060 break; 00061 case _T('='): 00062 kind = Value; 00063 ++token_; 00064 break; 00065 default: 00066 kind = Name; 00067 break; 00068 } 00069 if (kind == Option || kind == Value) 00070 token_ += _tcsspn(token_, white_space); // Skip any more whitespace 00071 if (*token_ == _T('"')) 00072 { 00073 const TCHAR* next = _tcschr(token_+1, _T('"')); 00074 if ( next ) 00075 { 00076 result.assign( token_+1, next ); 00077 next_token_ = next+1; 00078 return kind; 00079 } 00080 } 00081 next_token_ = token_ + _tcscspn(token_, terminators); 00082 result.assign(token_, next_token_); 00083 return kind; 00084 } 00085 00086 void reset() 00087 { 00088 token_ = 0; 00089 next_token_ = cmd_line_; 00090 } 00091 00092 private: 00093 const TCHAR* cmd_line_; 00094 const TCHAR* token_; 00095 const TCHAR* next_token_; 00096 }; 00098 00099 } 00100 00101 #endif