ConfigReader.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #pragma once
  2. #include <string>
  3. #include <fstream>
  4. #include <sstream>
  5. #include <map>
  6. class ConfigReader {
  7. public:
  8. bool load(const std::string& filename) {
  9. std::ifstream file(filename);
  10. if (!file.is_open()) {
  11. return false;
  12. }
  13. config_.clear();
  14. std::string line;
  15. std::string currentSection;
  16. while (std::getline(file, line)) {
  17. // 移除前后空格
  18. line.erase(0, line.find_first_not_of(" \t"));
  19. line.erase(line.find_last_not_of(" \t") + 1);
  20. // 跳过空行和注释
  21. if (line.empty() || line[0] == ';' || line[0] == '#') {
  22. continue;
  23. }
  24. // 处理节
  25. if (line[0] == '[' && line[line.length() - 1] == ']') {
  26. currentSection = line.substr(1, line.length() - 2);
  27. continue;
  28. }
  29. // 处理键值对
  30. size_t pos = line.find('=');
  31. if (pos != std::string::npos) {
  32. std::string key = line.substr(0, pos);
  33. std::string value = line.substr(pos + 1);
  34. // 移除键值前后的空格
  35. key.erase(0, key.find_first_not_of(" \t"));
  36. key.erase(key.find_last_not_of(" \t") + 1);
  37. value.erase(0, value.find_first_not_of(" \t"));
  38. value.erase(value.find_last_not_of(" \t") + 1);
  39. std::string fullKey = currentSection.empty() ? key : currentSection + "." + key;
  40. config_[fullKey] = value;
  41. }
  42. }
  43. file.close();
  44. return true;
  45. }
  46. std::string getString(const std::string& key, const std::string& defaultValue = "") {
  47. auto it = config_.find(key);
  48. return it != config_.end() ? it->second : defaultValue;
  49. }
  50. int getInt(const std::string& key, int defaultValue = 0) {
  51. auto it = config_.find(key);
  52. if (it != config_.end()) {
  53. try {
  54. return std::stoi(it->second);
  55. }
  56. catch (...) {
  57. return defaultValue;
  58. }
  59. }
  60. return defaultValue;
  61. }
  62. bool getBool(const std::string& key, bool defaultValue = false) {
  63. auto it = config_.find(key);
  64. if (it != config_.end()) {
  65. std::string value = it->second;
  66. for (auto& c : value) c = std::tolower(c);
  67. return value == "true" || value == "1" || value == "yes";
  68. }
  69. return defaultValue;
  70. }
  71. private:
  72. std::map<std::string, std::string> config_;
  73. };