以下是一个简单的示例代码,用于读取INI文件。

#include <iostream>
#include <fstream>
#include <string>
#include <map>

using namespace std;

int main() {
    // 打开INI文件
    ifstream fin("config.ini");
    if (!fin) {
        cerr << "无法打开INI文件!" << endl;
        return 1;
    }

    // 定义存储INI数据的map
    map<string, map<string, string>> data;

    // 定义当前正在处理的section名称
    string current_section;

    // 逐行读取INI文件
    string line;
    while (getline(fin, line)) {
        // 去除行首和行尾的空白字符
        line.erase(0, line.find_first_not_of(" \t\r\n"));
        line.erase(line.find_last_not_of(" \t\r\n") + 1);

        // 跳过注释行和空行
        if (line.empty() || line[0] == ';') {
            continue;
        }

        // 处理section行
        if (line[0] == '[' && line[line.size() - 1] == ']') {
            current_section = line.substr(1, line.size() - 2);
            data[current_section];
            continue;
        }

        // 处理key-value行
        size_t pos = line.find('=');
        if (pos != string::npos) {
            string key = line.substr(0, pos);
            string value = line.substr(pos + 1);
            data[current_section][key] = value;
        }
    }

    // 输出读取到的数据
    for (const auto& section : data) {
        cout << "[" << section.first << "]" << endl;
        for (const auto& key_value : section.second) {
            cout << key_value.first << " = " << key_value.second << endl;
        }
        cout << endl;
    }

    return 0;
}

该代码使用map来存储INI文件中的数据,其中外层map的key为section名称,value为内层map,内层map的key为key名称,value为key对应的值。在读取INI文件时,逐行解析文件内容,根据行的内容分别处理section行和key-value行。最后输出读取到的数据。

注意:该代码只是一个简单的示例,没有对INI文件格式进行严格的检查和处理,不适用于所有INI文件。在实际使用中,应根据INI文件的具体格式和要求进行相应的处理。

读ini文件用c++

原文地址: https://www.cveoy.top/t/topic/bIna 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录