Files
Lixinzhe_lib/Log/ConfigParser.cpp
2025-06-16 08:52:40 +08:00

71 lines
1.8 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "ConfigParser.h"
#include <fstream>
#include <iostream>
#include <algorithm>
#include <cctype>
using namespace std;
/** 清理字符串前后空格 */
void trim(std::string &s) {
auto wsfront = std::find_if_not(s.begin(), s.end(), [](int c) {
return std::isspace(c);
});
auto wsback = std::find_if_not(s.rbegin(), s.rend(), [](int c) {
return std::isspace(c);
}).base();
s = (wsback <= wsfront) ? std::string() : std::string(wsfront, wsback);
}
CPStatus configFromIni(const std::string &path, std::unordered_map<std::string, std::string> &config) {
CPStatus result = CPSUCCESS;
//打开文件
ifstream file(path);
if (!file.is_open()) {
result = CPFILE;
return result;
}
// 一次性读取整个文件减少I/O操作
file.seekg(0, std::ios::end);
size_t size = file.tellg();
file.seekg(0, std::ios::beg);
string m_buffer;
m_buffer.resize(size);
file.read(&m_buffer[0], static_cast<long long>(size));
//处理全部数据
config.clear();
std::string line;
line.reserve(256); // 预分配行缓存
for (auto it = m_buffer.cbegin(); it != m_buffer.cend();) {
// 快速跳过空白行
while (it != m_buffer.cend() && (*it == '\r' || *it == '\n')) { ++it; }
if (it == m_buffer.cend()) break;
// 获取行内容
line.clear();
while (it != m_buffer.cend() && *it != '\r' && *it != '\n' && *it != '\0') {
line += *it++;
}
//处理行内容
// 跳过空行和注释
if (line.empty() || line[0] == ';' || line[0] == '#') {
++it;
continue;
}
// 分割键值对
size_t eq_pos = line.find('=');
if (eq_pos != std::string::npos) {
std::string key = line.substr(0, eq_pos);
std::string value = line.substr(eq_pos + 1);
trim(key);
trim(value);
if (!key.empty()) {
config[key] = value; // 移动语义自动优化
}
}
}
return result;
}