首页
社区
课程
招聘
[原创]Ini解析器
发表于: 9小时前 175

[原创]Ini解析器

9小时前
175

Ini解析器,代码如下:

#pragma once
#include <string>
#include <map>
#include <iostream>

using namespace std;

class Value
{
public:
    Value();
    Value(bool value);
    Value(int value);
    Value(double value);
    Value(const char* value);
    Value(const string& value);

    void operator=(bool value);
    void operator=(int value);
    void operator=(double value);
    void operator=(const char* value);
    void operator=(const string& value);

    operator bool() const;
    operator int() const;
    operator double() const;
    operator string() const;
private:
    string m_value;
};

typedef std::map<string, Value> Section;

class IniFile {
public:
    IniFile() = default;
    bool load(const string& filename);

    Value& get(const string& section, const string& key);

    void set(const string& section, const string& key, bool value);
    void set(const string& section, const string& key, int value);
    void set(const string& section, const string& key, double value);
    void set(const string& section, const string& key, const char* value);
    void set(const string& section, const string& key, const string& value); // 修正:由指针改为引用
    void set(const string& section, const string& key, const Value& value);

    bool has(const string& section, const string& key) const; // 优化:加 const
    bool has(const string& section) const;                    // 优化:加 const

    void remove(const string& section, const string& key);
    void remove(const string& section);

    void clear();
    void show() const;                                        // 优化:加 const
    bool save(const string& filename);
    string str() const;                                       // 优化:加 const

    Section& operator[](const string& section) {
        return m_sections[section];
    }

private:
    string trim(string s);

private:
    string m_filename;
    std::map<string, Section> m_sections;
};
#include "IniFile.h"
#include <sstream>
#include <fstream>
#include <cstdlib>

Value::Value() : m_value("") {}

Value::Value(bool value) {
    m_value = value ? "true" : "false";
}

Value::Value(int value) {
    m_value = std::to_string(value); // 优化:相比 stringstream,to_string 更高效
}

Value::Value(double value) {
    m_value = std::to_string(value);
}

Value::Value(const char* value) : m_value(value ? value : "") {}

Value::Value(const string& value) : m_value(value) {}

void Value::operator=(bool value) {
    m_value = value ? "true" : "false";
}

void Value::operator=(int value) {
    m_value = std::to_string(value);
}

void Value::operator=(double value) {
    m_value = std::to_string(value);
}

void Value::operator=(const char* value) {
    m_value = value ? value : "";
}

void Value::operator=(const string& value) {
    m_value = value;
}

Value::operator bool() const {
    return m_value == "true" || m_value == "1";
}

Value::operator int() const {
    return m_value.empty() ? 0 : std::atoi(m_value.c_str());
}

Value::operator double() const {
    return m_value.empty() ? 0.0 : std::atof(m_value.c_str());
}

Value::operator string() const {
    return m_value;
}

// ================= IniFile 实现 =================

bool IniFile::load(const string& filename) {
    m_filename = filename;
    ifstream fin(filename);
    if (fin.fail()) {
        return false;
    }

    string line;
    string section = "";
    while (std::getline(fin, line)) {
        line = trim(line);
        // 优化:支持忽略空行及注释行(; 或 #)
        if (line.empty() || line[0] == ';' || line[0] == '#') {
            continue;
        }

        if (line[0] == '[') {
            size_t pos = line.find_first_of(']');
            if (pos != string::npos && pos > 1) { // 健壮性安全检查
                section = line.substr(1, pos - 1);
                section = trim(section);
                // 确保 Section 存在
                if (m_sections.find(section) == m_sections.end()) {
                    m_sections[section] = Section();
                }
            }
        }
        else {
            size_t pos = line.find_first_of('=');
            if (pos != string::npos && !section.empty()) { // 健壮性安全检查
                string key = line.substr(0, pos);
                string value = line.substr(pos + 1);
                m_sections[section][trim(key)] = trim(value);
            }
        }
    }
    fin.close();
    return true;
}

Value& IniFile::get(const string& section, const string& key) {
    return m_sections[section][key];
}

void IniFile::set(const string& section, const string& key, bool value) {
    m_sections[section][key] = value;
}

void IniFile::set(const string& section, const string& key, int value) {
    m_sections[section][key] = value;
}

void IniFile::set(const string& section, const string& key, double value) {
    m_sections[section][key] = value;
}

void IniFile::set(const string& section, const string& key, const char* value) {
    m_sections[section][key] = value;
}

void IniFile::set(const string& section, const string& key, const string& value) {
    m_sections[section][key] = value;
}

void IniFile::set(const string& section, const string& key, const Value& value) {
    m_sections[section][key] = value;
}

bool IniFile::has(const string& section, const string& key) const {
    auto it = m_sections.find(section);
    if (it != m_sections.end()) {
        return (it->second.find(key) != it->second.end()); // 修正:由 == 改为 !=
    }
    return false;
}

bool IniFile::has(const string& section) const {
    return (m_sections.find(section) != m_sections.end());
}

void IniFile::remove(const string& section, const string& key) {
    auto it = m_sections.find(section);
    if (it != m_sections.end()) {
        it->second.erase(key);
    }
}

void IniFile::remove(const string& section) {
    m_sections.erase(section);
}

void IniFile::clear() {
    m_sections.clear();
}

void IniFile::show() const {
    std::cout << str(); // 直接复用 str() 的逻辑
}

bool IniFile::save(const string& filename) {
    ofstream fout(filename);
    if (fout.fail()) {
        return false;
    }
    fout << str();
    fout.close();
    return true; // 修正:补全返回值
}

string IniFile::str() const {
    stringstream ss;
    // 优化:使用现代化基于范围的 for 循环
    for (const auto& sec_pair : m_sections) {
        ss << "[" << sec_pair.first << "]" << std::endl;
        for (const auto& val_pair : sec_pair.second) {
            ss << val_pair.first << " = " << string(val_pair.second) << std::endl;
        }
        ss << std::endl;
    }
    return ss.str();
}

string IniFile::trim(string s) {
    size_t first = s.find_first_not_of(" \n\r\t");
    if (first == string::npos) return "";
    size_t last = s.find_last_not_of(" \n\r\t");
    return s.substr(first, (last - first + 1));
}

最后是main函数:

#include <iostream>
#include "IniFile.h"

int main()
{
    // 测试 Value 基础赋值
    Value v1(true);
    Value v2(123);
    Value v3(1.23);
    Value v4("hello world");

    Value v5; v5 = true;
    Value v6; v6 = 123;
    Value v7; v7 = 1.23;
    Value v8; v8 = "hello world";

    IniFile ini;
    if (ini.load("./main.ini")) {
        // 测试常规 get 
        // 修正说明:原代码读取的键值有些在 main.ini 中是数字,这里根据实际文件内容提取
        string enabled = (string)ini.get("AimBot", "Enabled");
        double smooth = (double)ini.get("AimBot", "Smooth");
        bool flag = (bool)ini.get("AimBot", "flag");

        cout << "--- 显式 Get 测试 ---" << endl;
        cout << "Enabled: " << enabled << ", Smooth: " << smooth << ", Flag: " << flag << endl << endl;

        // 测试重载 [] 运算符
        // 修正说明:修改变量名防止与上面重名冲突;改为匹配 main.ini 中的实际 Section [Network]
        const string& ip = ini["Network"]["ServerIP"];
        int port = ini["Network"]["Port"];

        cout << "--- 运算符 [] 测试 ---" << endl;
        cout << "IP: " << ip << endl;
        cout << "Port: " << port << endl << endl;

        // 测试写入功能
        ini.set("Network", "Timeout", 1000);
        ini.set("Network", "SecureMode", true);

        // 测试 Has 功能(已经修复了 has 的底层 Bug)
        bool hasTimeout = ini.has("Network", "Timeout");
        bool hasFakeSection = ini.has("Server_Fake_123");

        cout << "--- 状态检测 测试 ---" << endl;
        cout << "Has Timeout?: " << (hasTimeout ? "Yes" : "No") << endl;
        cout << "Has FakeSection?: " << (hasFakeSection ? "Yes" : "No") << endl << endl;
    }
    else {
        cout << "无法加载配置文件" << endl;
    }

    cout << "--- 打印当前全量配置 ---" << endl;
    ini.show();

    // 顺手测试一下保存功能
    ini.save("./main_modified.ini");

    return 0;
}

附加的ini文件:

[AimBot]
Enabled=1
Smooth=0.65
Threshold=0.85
TargetBone=1
flag=true
[PID_Settings]
Kp=0.45
Ki=0.01
Kd=0.005

[Display]
WindowTitle=DeltaForce_Internal_Overlay
DebugMode=true
MaxFPS=144

[Network]
ServerIP=127.0.0.1
Port=8888



[培训]《冰与火的战歌:Windows内核攻防实战》!从零到实战,融合AI与Windows内核攻防全技术栈,打造具备自动化能力的内核开发高手。

收藏
免费 0
打赏
分享
最新回复 (0)
游客
登录 | 注册 方可回帖
返回