iniparser.h 2.5 KB

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