| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- #pragma once
- #include <string>
- #include <fstream>
- #include <sstream>
- #include <map>
- class ConfigReader {
- public:
- bool load(const std::string& filename) {
- std::ifstream file(filename);
- if (!file.is_open()) {
- return false;
- }
- config_.clear();
- std::string line;
- std::string currentSection;
- while (std::getline(file, line)) {
- // 移除前后空格
- line.erase(0, line.find_first_not_of(" \t"));
- line.erase(line.find_last_not_of(" \t") + 1);
- // 跳过空行和注释
- if (line.empty() || line[0] == ';' || line[0] == '#') {
- continue;
- }
- // 处理节
- if (line[0] == '[' && line[line.length() - 1] == ']') {
- currentSection = line.substr(1, line.length() - 2);
- continue;
- }
- // 处理键值对
- size_t pos = line.find('=');
- if (pos != std::string::npos) {
- std::string key = line.substr(0, pos);
- std::string value = line.substr(pos + 1);
- // 移除键值前后的空格
- key.erase(0, key.find_first_not_of(" \t"));
- key.erase(key.find_last_not_of(" \t") + 1);
- value.erase(0, value.find_first_not_of(" \t"));
- value.erase(value.find_last_not_of(" \t") + 1);
- std::string fullKey = currentSection.empty() ? key : currentSection + "." + key;
- config_[fullKey] = value;
- }
- }
- file.close();
- return true;
- }
- std::string getString(const std::string& key, const std::string& defaultValue = "") {
- auto it = config_.find(key);
- return it != config_.end() ? it->second : defaultValue;
- }
- int getInt(const std::string& key, int defaultValue = 0) {
- auto it = config_.find(key);
- if (it != config_.end()) {
- try {
- return std::stoi(it->second);
- }
- catch (...) {
- return defaultValue;
- }
- }
- return defaultValue;
- }
- bool getBool(const std::string& key, bool defaultValue = false) {
- auto it = config_.find(key);
- if (it != config_.end()) {
- std::string value = it->second;
- for (auto& c : value) c = std::tolower(c);
- return value == "true" || value == "1" || value == "yes";
- }
- return defaultValue;
- }
- private:
- std::map<std::string, std::string> config_;
- };
|