手机版
你好,游客 登录 注册
背景:
阅读新闻

C++实现的命令行参数管理

[日期:2012-11-27] 来源:Linux社区  作者:zmxiangde_88 [字体:大 中 小]

源码下载地址:

免费下载地址在 http://linux.linuxidc.com/

用户名与密码都是www.linuxidc.com

具体下载目录在 /2012年资料/11月/27日/C++实现的命令行参数管理

粘贴如下:

flags.h

  1. #ifndef TALK_BASE_FLAGS_H__  
  2. #define TALK_BASE_FLAGS_H__  
  3.  
  4. #include <assert.h>  
  5.  
  6. #include "talk/base/checks.h"  
  7. #include "talk/base/common.h"  
  8.  
  9. // Internal use only.  
  10. union FlagValue { 
  11.   // Note: Because in C++ non-bool values are silently converted into  
  12.   // bool values ('bool b = "false";' results in b == true!), we pass  
  13.   // and int argument to New_BOOL as this appears to be safer - sigh.  
  14.   // In particular, it prevents the (not uncommon!) bug where a bool  
  15.   // flag is defined via: DEFINE_bool(flag, "false", "some comment");.  
  16.   static FlagValue New_BOOL(int b) { 
  17.     FlagValue v; 
  18.     v.b = (b != 0); 
  19.     return v; 
  20.   } 
  21.  
  22.   static FlagValue New_INT(int i) { 
  23.     FlagValue v; 
  24.     v.i = i; 
  25.     return v; 
  26.   } 
  27.  
  28.   static FlagValue New_FLOAT(float f) { 
  29.     FlagValue v; 
  30.     v.f = f; 
  31.     return v; 
  32.   } 
  33.  
  34.   static FlagValue New_STRING(const char* s) { 
  35.     FlagValue v; 
  36.     v.s = s; 
  37.     return v; 
  38.   } 
  39.  
  40.   bool b; 
  41.   int i; 
  42.   double f; 
  43.   const char* s; 
  44. }; 
  45.  
  46.  
  47. // Each flag can be accessed programmatically via a Flag object.  
  48. class Flag { 
  49.  public: 
  50.   enum Type { BOOL, INT, FLOAT, STRING }; 
  51.  
  52.   // Internal use only.  
  53.   Flag(const char* file, const char* name, const char* comment, 
  54.        Type type, void* variable, FlagValue default_); 
  55.  
  56.   // General flag information  
  57.   const char* file() const  { return file_; } 
  58.   const char* name() const  { return name_; } 
  59.   const char* comment() const  { return comment_; } 
  60.  
  61.   // Flag type  
  62.   Type type() const  { return type_; } 
  63.  
  64.   // Flag variables  
  65.   bool* bool_variable() const { 
  66.     assert(type_ == BOOL); 
  67.     return &variable_->b; 
  68.   } 
  69.    
  70.   int* int_variable() const { 
  71.     assert(type_ == INT); 
  72.     return &variable_->i; 
  73.   } 
  74.    
  75.   double* float_variable() const { 
  76.     assert(type_ == FLOAT); 
  77.     return &variable_->f; 
  78.   } 
  79.    
  80.   const char** string_variable() const { 
  81.     assert(type_ == STRING); 
  82.     return &variable_->s; 
  83.   } 
  84.  
  85.   // Default values  
  86.   bool bool_default() const { 
  87.     assert(type_ == BOOL); 
  88.     return default_.b; 
  89.   } 
  90.    
  91.   int int_default() const { 
  92.     assert(type_ == INT); 
  93.     return default_.i; 
  94.   } 
  95.    
  96.   double float_default() const { 
  97.     assert(type_ == FLOAT); 
  98.     return default_.f; 
  99.   } 
  100.    
  101.   const char* string_default() const { 
  102.     assert(type_ == STRING); 
  103.     return default_.s; 
  104.   } 
  105.  
  106.   // Resets a flag to its default value  
  107.   void SetToDefault(); 
  108.  
  109.   // Iteration support  
  110.   Flag* next() const  { return next_; } 
  111.  
  112.   // Prints flag information. The current flag value is only printed  
  113.   // if print_current_value is set.  
  114.   void Print(bool print_current_value); 
  115.  
  116.  private: 
  117.   const char* file_; 
  118.   const char* name_; 
  119.   const char* comment_; 
  120.  
  121.   Type type_; 
  122.   FlagValue* variable_; 
  123.   FlagValue default_; 
  124.  
  125.   Flag* next_; 
  126.  
  127.   friend class FlagList;  // accesses next_  
  128. }; 
  129.  
  130.  
  131. // Internal use only.  
  132. #define DEFINE_FLAG(type, c_type, name, default, comment) \  
  133.   /* define and initialize the flag */                    \ 
  134.   c_type FLAG_##name = (default);                         \ 
  135.   /* register the flag */                                 \ 
  136.   static Flag Flag_##name(__FILE__, #name, (comment),   \ 
  137.                           Flag::type, &FLAG_##name,       \ 
  138.                           FlagValue::New_##type(default)) 
  139.  
  140.  
  141. // Internal use only.  
  142. #define DECLARE_FLAG(c_type, name)              \  
  143.   /* declare the external flag */               \ 
  144.   extern c_type FLAG_##name 
  145.  
  146.  
  147. // Use the following macros to define a new flag:  
  148. #define DEFINE_bool(name, default, comment) \  
  149.   DEFINE_FLAG(BOOL, bool, name, default, comment) 
  150. #define DEFINE_int(name, default, comment) \  
  151.   DEFINE_FLAG(INT, int, name, default, comment) 
  152. #define DEFINE_float(name, default, comment) \  
  153.   DEFINE_FLAG(FLOAT, double, name, default, comment) 
  154. #define DEFINE_string(name, default, comment) \  
  155.   DEFINE_FLAG(STRING, const char*, name, default, comment) 
  156.  
  157.  
  158. // Use the following macros to declare a flag defined elsewhere:  
  159. #define DECLARE_bool(name)  DECLARE_FLAG(bool, name)  
  160. #define DECLARE_int(name)  DECLARE_FLAG(int, name)  
  161. #define DECLARE_float(name)  DECLARE_FLAG(double, name)  
  162. #define DECLARE_string(name)  DECLARE_FLAG(const char*, name)  
  163.  
  164.  
  165. // The global list of all flags.  
  166. class FlagList { 
  167.  public: 
  168.   FlagList(); 
  169.  
  170.   // The NULL-terminated list of all flags. Traverse with Flag::next().  
  171.   static Flag* list()  { return list_; } 
  172.  
  173.   // If file != NULL, prints information for all flags defined in file;  
  174.   // otherwise prints information for all flags in all files. The current  
  175.   // flag value is only printed if print_current_value is set.  
  176.   static void Print(const char* file, bool print_current_value); 
  177.  
  178.   // Lookup a flag by name. Returns the matching flag or NULL.  
  179.   static Flag* Lookup(const char* name); 
  180.  
  181.   // Helper function to parse flags: Takes an argument arg and splits it into  
  182.   // a flag name and flag value (or NULL if they are missing). is_bool is set  
  183.   // if the arg started with "-no" or "--no". The buffer may be used to NUL-  
  184.   // terminate the name, it must be large enough to hold any possible name.  
  185.   static void SplitArgument(const char* arg, 
  186.                             char* buffer, int buffer_size, 
  187.                             const char** name, const char** value, 
  188.                             bool* is_bool); 
  189.  
  190.   // Set the flag values by parsing the command line. If remove_flags  
  191.   // is set, the flags and associated values are removed from (argc,  
  192.   // argv). Returns 0 if no error occurred. Otherwise, returns the  
  193.   // argv index > 0 for the argument where an error occurred. In that  
  194.   // case, (argc, argv) will remain unchanged indepdendent of the  
  195.   // remove_flags value, and no assumptions about flag settings should  
  196.   // be made.  
  197.   //  
  198.   // The following syntax for flags is accepted (both '-' and '--' are ok):  
  199.   //  
  200.   //   --flag        (bool flags only)  
  201.   //   --noflag      (bool flags only)  
  202.   //   --flag=value  (non-bool flags only, no spaces around '=')  
  203.   //   --flag value  (non-bool flags only)  
  204.   static int SetFlagsFromCommandLine(int* argc, 
  205.                                      const char** argv, 
  206.                                      bool remove_flags); 
  207.   static inline int SetFlagsFromCommandLine(int* argc, 
  208.                                             char** argv, 
  209.                                             bool remove_flags) { 
  210.     return SetFlagsFromCommandLine(argc, const_cast<const char**>(argv), 
  211.                                    remove_flags); 
  212.   } 
  213.  
  214.   // Registers a new flag. Called during program initialization. Not  
  215.   // thread-safe.  
  216.   static void Register(Flag* flag); 
  217.  
  218.  private: 
  219.   static Flag* list_; 
  220. }; 
  221.  
  222. #ifdef WIN32  
  223. // A helper class to translate Windows command line arguments into UTF8,  
  224. // which then allows us to just pass them to the flags system.  
  225. // This encapsulates all the work of getting the command line and translating  
  226. // it to an array of 8-bit strings; all you have to do is create one of these,  
  227. // and then call argc() and argv().  
  228. class WindowsCommandLineArguments { 
  229.  public: 
  230.   WindowsCommandLineArguments(); 
  231.   ~WindowsCommandLineArguments(); 
  232.  
  233.   int argc() { return argc_; } 
  234.   char **argv() { return argv_; } 
  235.  private: 
  236.   int argc_; 
  237.   char **argv_; 
  238.  
  239.  private: 
  240.   DISALLOW_EVIL_CONSTRUCTORS(WindowsCommandLineArguments); 
  241. }; 
  242. #endif  // WIN32  
  243.  
  244.  
  245. #endif  // SHARED_COMMANDLINEFLAGS_FLAGS_H__ 

flags.cc 

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <string.h>  
  4.  
  5.  
  6. #ifdef WIN32  
  7. #include "talk/base/win32.h"  
  8. #include <shellapi.h>  
  9. #endif  
  10.  
  11. #include "talk/base/flags.h"  
  12.  
  13.  
  14. // -----------------------------------------------------------------------------  
  15. // Implementation of Flag  
  16.  
  17. Flag::Flag(const char* file, const char* name, const char* comment, 
  18.            Type type, void* variable, FlagValue default__) 
  19.     : file_(file), 
  20.       name_(name), 
  21.       comment_(comment), 
  22.       type_(type), 
  23.       variable_(reinterpret_cast<FlagValue*>(variable)), 
  24.       default_(default__) { 
  25.   FlagList::Register(this); 
  26. } 
  27.  
  28.  
  29. void Flag::SetToDefault() { 
  30.   // Note that we cannot simply do '*variable_ = default_;' since  
  31.   // flag variables are not really of type FlagValue and thus may  
  32.   // be smaller! The FlagValue union is simply 'overlayed' on top  
  33.   // of a flag variable for convenient access. Since union members  
  34.   // are guarantee to be aligned at the beginning, this works.  
  35.   switch (type_) { 
  36.     case Flag::BOOL: 
  37.       variable_->b = default_.b; 
  38.       return; 
  39.     case Flag::INT: 
  40.       variable_->i = default_.i; 
  41.       return; 
  42.     case Flag::FLOAT: 
  43.       variable_->f = default_.f; 
  44.       return; 
  45.     case Flag::STRING: 
  46.       variable_->s = default_.s; 
  47.       return; 
  48.   } 
  49.   UNREACHABLE(); 
  50. } 
  51.  
  52.  
  53. static const char* Type2String(Flag::Type type) { 
  54.   switch (type) { 
  55.     case Flag::BOOL: return "bool"; 
  56.     case Flag::INT: return "int"; 
  57.     case Flag::FLOAT: return "float"; 
  58.     case Flag::STRING: return "string"; 
  59.   } 
  60.   UNREACHABLE(); 
  61.   return NULL; 
  62. } 
  63.  
  64.  
  65. static void PrintFlagValue(Flag::Type type, FlagValue* p) { 
  66.   switch (type) { 
  67.     case Flag::BOOL: 
  68.       printf("%s", (p->b ? "true" : "false")); 
  69.       return; 
  70.     case Flag::INT: 
  71.       printf("%d", p->i); 
  72.       return; 
  73.     case Flag::FLOAT: 
  74.       printf("%f", p->f); 
  75.       return; 
  76.     case Flag::STRING: 
  77.       printf("%s", p->s); 
  78.       return; 
  79.   } 
  80.   UNREACHABLE(); 
  81. } 
  82.  
  83.  
  84. void Flag::Print(bool print_current_value) { 
  85.   printf("  --%s (%s)  type: %s  default: ", name_, comment_, 
  86.           Type2String(type_)); 
  87.   PrintFlagValue(type_, &default_); 
  88.   if (print_current_value) { 
  89.     printf("  current value: "); 
  90.     PrintFlagValue(type_, variable_); 
  91.   } 
  92.   printf("\n"); 
  93. } 
  94.  
  95.  
  96. // -----------------------------------------------------------------------------  
  97. // Implementation of FlagList  
  98.  
  99. Flag* FlagList::list_ = NULL; 
  100.  
  101.  
  102. FlagList::FlagList() { 
  103.   list_ = NULL; 
  104. } 
  105.  
  106. void FlagList::Print(const char* file, bool print_current_value) { 
  107.   // Since flag registration is likely by file (= C++ file),  
  108.   // we don't need to sort by file and still get grouped output.  
  109.   const char* current = NULL; 
  110.   for (Flag* f = list_; f != NULL; f = f->next()) { 
  111.     if (file == NULL || file == f->file()) { 
  112.       if (current != f->file()) { 
  113.         printf("Flags from %s:\n", f->file()); 
  114.         current = f->file(); 
  115.       } 
  116.       f->Print(print_current_value); 
  117.     } 
  118.   } 
  119. } 
  120.  
  121.  
  122. Flag* FlagList::Lookup(const char* name) { 
  123.   Flag* f = list_; 
  124.   while (f != NULL && strcmp(name, f->name()) != 0) 
  125.     f = f->next(); 
  126.   return f; 
  127. } 
  128.  
  129.  
  130. void FlagList::SplitArgument(const char* arg, 
  131.                              char* buffer, int buffer_size, 
  132.                              const char** name, const char** value, 
  133.                              bool* is_bool) { 
  134.   *name = NULL; 
  135.   *value = NULL; 
  136.   *is_bool = false; 
  137.  
  138.   if (*arg == '-') { 
  139.     // find the begin of the flag name  
  140.     arg++;  // remove 1st '-'  
  141.     if (*arg == '-') 
  142.       arg++;  // remove 2nd '-'  
  143.     if (arg[0] == 'n' && arg[1] == 'o') { 
  144.       arg += 2;  // remove "no"  
  145.       *is_bool = true; 
  146.     } 
  147.     *name = arg; 
  148.  
  149.     // find the end of the flag name  
  150.     while (*arg != '\0' && *arg != '=') 
  151.       arg++; 
  152.  
  153.     // get the value if any  
  154.     if (*arg == '=') { 
  155.       // make a copy so we can NUL-terminate flag name  
  156.       int n = static_cast<int>(arg - *name); 
  157.       if (n >= buffer_size) 
  158.         Fatal(__FILE__, __LINE__, "CHECK(%s) failed", "n < buffer_size"); 
  159.       memcpy(buffer, *name, n * sizeof(char)); 
  160.       buffer[n] = '\0'; 
  161.       *name = buffer; 
  162.       // get the value  
  163.       *value = arg + 1; 
  164.     } 
  165.   } 
  166. } 
  167.  
  168.  
  169. int FlagList::SetFlagsFromCommandLine(int* argc, const char** argv, 
  170.                                       bool remove_flags) { 
  171.   // parse arguments  
  172.   for (int i = 1; i < *argc; /* see below */) { 
  173.     int j = i;  // j > 0  
  174.     const char* arg = argv[i++]; 
  175.  
  176.     // split arg into flag components  
  177.     char buffer[1024]; 
  178.     const char* name; 
  179.     const char* value; 
  180.     bool is_bool; 
  181.     SplitArgument(arg, buffer, sizeof buffer, &name, &value, &is_bool); 
  182.  
  183.     if (name != NULL) { 
  184.       // lookup the flag  
  185.       Flag* flag = Lookup(name); 
  186.       if (flag == NULL) { 
  187.         fprintf(stderr, "Error: unrecognized flag %s\n", arg); 
  188.         return j; 
  189.       } 
  190.  
  191.       // if we still need a flag value, use the next argument if available  
  192.       if (flag->type() != Flag::BOOL && value == NULL) { 
  193.         if (i < *argc) { 
  194.           value = argv[i++]; 
  195.         } else { 
  196.           fprintf(stderr, "Error: missing value for flag %s of type %s\n", 
  197.             arg, Type2String(flag->type())); 
  198.           return j; 
  199.         } 
  200.       } 
  201.  
  202.       // set the flag  
  203.       char empty[] = { '\0' }; 
  204.       char* endp = empty; 
  205.       switch (flag->type()) { 
  206.         case Flag::BOOL: 
  207.           *flag->bool_variable() = !is_bool; 
  208.           break; 
  209.         case Flag::INT: 
  210.           *flag->int_variable() = strtol(value, &endp, 10); 
  211.           break; 
  212.         case Flag::FLOAT: 
  213.           *flag->float_variable() = strtod(value, &endp); 
  214.           break; 
  215.         case Flag::STRING: 
  216.           *flag->string_variable() = value; 
  217.           break; 
  218.       } 
  219.  
  220.       // handle errors  
  221.       if ((flag->type() == Flag::BOOL && value != NULL) || 
  222.           (flag->type() != Flag::BOOL && is_bool) || 
  223.           *endp != '\0') { 
  224.         fprintf(stderr, "Error: illegal value for flag %s of type %s\n", 
  225.           arg, Type2String(flag->type())); 
  226.         return j; 
  227.       } 
  228.  
  229.       // remove the flag & value from the command  
  230.       if (remove_flags) 
  231.         while (j < i) 
  232.           argv[j++] = NULL; 
  233.     } 
  234.   } 
  235.  
  236.   // shrink the argument list  
  237.   if (remove_flags) { 
  238.     int j = 1; 
  239.     for (int i = 1; i < *argc; i++) { 
  240.       if (argv[i] != NULL) 
  241.         argv[j++] = argv[i]; 
  242.     } 
  243.     *argc = j; 
  244.   } 
  245.  
  246.   // parsed all flags successfully  
  247.   return 0; 
  248. } 
  249.  
  250. void FlagList::Register(Flag* flag) { 
  251.   assert(flag != NULL && strlen(flag->name()) > 0); 
  252.   if (Lookup(flag->name()) != NULL) 
  253.     Fatal(flag->file(), 0, "flag %s declared twice", flag->name()); 
  254.   flag->next_ = list_; 
  255.   list_ = flag; 
  256. } 
  257.  
  258. #ifdef WIN32  
  259. WindowsCommandLineArguments::WindowsCommandLineArguments() { 
  260.   // start by getting the command line.  
  261.   LPTSTR command_line = ::GetCommandLine(); 
  262.    // now, convert it to a list of wide char strings.  
  263.   LPWSTR *wide_argv = ::CommandLineToArgvW(command_line, &argc_); 
  264.   // now allocate an array big enough to hold that many string pointers.  
  265.   argv_ = new char*[argc_]; 
  266.  
  267.   // iterate over the returned wide strings;  
  268.   for(int i = 0; i < argc_; ++i) { 
  269.     std::string s = talk_base::ToUtf8(wide_argv[i], wcslen(wide_argv[i])); 
  270.     char *buffer = new char[s.length() + 1]; 
  271.     talk_base::strcpyn(buffer, s.length() + 1, s.c_str()); 
  272.  
  273.     // make sure the argv array has the right string at this point.  
  274.     argv_[i] = buffer; 
  275.   } 
  276.   LocalFree(wide_argv); 
  277. } 
  278.  
  279. WindowsCommandLineArguments::~WindowsCommandLineArguments() { 
  280.   // need to free each string in the array, and then the array.  
  281.   for(int i = 0; i < argc_; i++) { 
  282.     delete[] argv_[i]; 
  283.   } 
  284.  
  285.   delete[] argv_; 
  286. } 
  287. #endif  // WIN32 
linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款