SoFunction
Updated on 2025-03-03

Implementation example of reading and writing ini files in c++ standard library

Below is a complete implementation of the INI file class, including the functions of reading and writing INI files.

1. Header file

#ifndef INIFILE_H
#define INIFILE_H

#include <string>
#include <map>
#include <fstream>
#include <sstream>

class IniFile {
public:
    // Constructor, accept file name    IniFile(const std::string& filename);

    // Load the contents of the INI file    void load();

    // Save content to INI file    void save() const;

    // Get the key value of the specified section    std::string getValue(const std::string& section, const std::string& key, const std::string& defaultValue = "") const;

    // Set the key value of the specified section    void setValue(const std::string& section, const std::string& key, const std::string& value);

private:
    std::string filename;  // INI file name    std::map<std::string, std::map<std::string, std::string>> data;  // Store sections and key-value pairs};

#endif // INIFILE_H

2. Implement the file

#include ""
#include <iostream>
#include <stdexcept>
#include <algorithm>

// Constructor, accept file nameIniFile::IniFile(const std::string& filename) : filename(filename) {
    load();  // Load the file contents}

// Load the contents of the INI filevoid IniFile::load() {
    std::ifstream file(filename);
    if (!file.is_open()) {
        throw std::runtime_error("Could not open file: " + filename);
    }

    std::string line;
    std::string currentSection;

    while (std::getline(file, line)) {
        // Remove comments and empty lines        (std::remove_if((), (), [](unsigned char c) { return std::isspace(c); }), ());
        if (() || line[0] == ';') {
            continue;  // Skip empty lines and comment lines        }

        // Processing Section        if (line[0] == '[') {
            auto endPos = (']');
            if (endPos != std::string::npos) {
                currentSection = (1, endPos - 1);  // Get the section name            }
            continue;
        }

        // Process key-value pairs        auto delimiterPos = ('=');
        if (delimiterPos != std::string::npos) {
            std::string key = (0, delimiterPos);
            std::string value = (delimiterPos + 1);
            data[currentSection][key] = value;  // Store key-value pairs        }
    }

    ();
}

// Save content to INI filevoid IniFile::save() const {
    std::ofstream file(filename);
    if (!file.is_open()) {
        throw std::runtime_error("Could not open file: " + filename);
    }

    for (const auto& section : data) {
        file << "[" <<  << "]\n";  // Write section        for (const auto& kv : ) {
            file <<  << "=" <<  << "\n";  // Write key-value pairs        }
        file << "\n";  // Blank lines between sections    }

    ();
}

// Get the key value of the specified sectionstd::string IniFile::getValue(const std::string& section, const std::string& key, const std::string& defaultValue) const {
    auto sectionIt = (section);
    if (sectionIt != ()) {
        auto keyIt = sectionIt->(key);
        if (keyIt != sectionIt->()) {
            return keyIt->second;  // Return the found value        }
    }
    return defaultValue;  // Return to the default value}

// Set the key value of the specified sectionvoid IniFile::setValue(const std::string& section, const std::string& key, const std::string& value) {
    data[section][key] = value;  // Set value}

3. Use examples

Here is a sample code for how to use the IniFile class:

#include <iostream>
#include ""

int main() {
    try {
        // Create an IniFile object and load an INI file        IniFile ini("");

        // Get key value        std::string username = ("UserSettings", "Username", "defaultUser");
        std::cout << "Username: " << username << std::endl;

        // Set new key value        ("UserSettings", "Username", "newUser");

        // Save to INI file        ();
        std::cout << "New username saved!" << std::endl;

    } catch (const std::exception& e) {
        std::cerr << "Error: " << () << std::endl;
    }

    return 0;
}

4. Description

  • File format: INI The file format is simple, consisting of sections (enclosed by []) and key-value pairs (key=value).
  • Loading: Read the file, parse sections and key-value pairs in the load() method.
  • Save: Write data back to the file in the save() method.
  • Error handling: Provides basic error handling, and throws an exception if the file cannot be opened.

This implementation can meet the general INI file reading and writing needs and can further expand functions as needed.

This is the article about the implementation example of reading and writing ini files in the C++ standard library. For more related contents of writing ini files in C++, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!