iniparser.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. #ifndef HW_INI_PARSER_H_
  2. #define HW_INI_PARSER_H_
  3. #include <list>
  4. #include <string>
  5. #include "hdef.h"
  6. #include "hstring.h"
  7. #define DEFAULT_INI_COMMENT "#"
  8. #define DEFAULT_INI_DELIM "="
  9. /**********************************
  10. # div
  11. [section]
  12. key = value # span
  13. # div
  14. ***********************************/
  15. // class IniComment;
  16. // class IniSection;
  17. // class IniKeyValue;
  18. // for simplicity, we add a member value.
  19. class IniNode {
  20. public:
  21. enum Type {
  22. INI_NODE_TYPE_UNKNOWN,
  23. INI_NODE_TYPE_ROOT,
  24. INI_NODE_TYPE_SECTION,
  25. INI_NODE_TYPE_KEY_VALUE,
  26. INI_NODE_TYPE_DIV,
  27. INI_NODE_TYPE_SPAN,
  28. } type;
  29. string label;
  30. string value;
  31. std::list<IniNode*> children;
  32. virtual ~IniNode() {
  33. for (auto& item : children) {
  34. SAFE_DELETE(item);
  35. }
  36. children.clear();
  37. }
  38. void Add(IniNode* pNode) {
  39. children.push_back(pNode);
  40. }
  41. void Del(IniNode* pNode) {
  42. for (auto iter = children.begin(); iter != children.end(); ++iter) {
  43. if ((*iter) == pNode) {
  44. delete (*iter);
  45. children.erase(iter);
  46. return;
  47. }
  48. }
  49. }
  50. IniNode* Get(const string& label, Type type = INI_NODE_TYPE_KEY_VALUE) {
  51. for (auto& pNode : children) {
  52. if (pNode->type == type && pNode->label == label) {
  53. return pNode;
  54. }
  55. }
  56. return NULL;
  57. }
  58. };
  59. // class IniComment : public IniNode {
  60. // public:
  61. // string comment;
  62. // };
  63. // class IniSection : public IniNode {
  64. // public:
  65. // string section;
  66. // };
  67. // class IniKeyValue : public IniNode {
  68. // public:
  69. // string key;
  70. // string value;
  71. // };
  72. class IniParser {
  73. public:
  74. IniParser();
  75. ~IniParser();
  76. void SetIniComment(const string& comment) {_comment = comment;}
  77. void SetIniDilim(const string& delim) {_delim = delim;}
  78. int LoadFromFile(const char* filepath);
  79. int LoadFromMem(const char* data);
  80. int Unload();
  81. void DumpString(IniNode* pNode, string& str);
  82. string DumpString();
  83. int Save();
  84. int SaveAs(const char* filepath);
  85. string GetValue(const string& key, const string& section = "");
  86. void SetValue(const string& key, const string& value, const string& section = "");
  87. private:
  88. string _comment;
  89. string _delim;
  90. string _filepath;
  91. IniNode* root_;
  92. };
  93. #endif // HW_INI_PARSER_H_