Skip to content

Instantly share code, notes, and snippets.

@MrSimbax
Last active Dec 21, 2021
Embed
What would you like to do?
Simple INI reading and writing in C++ (Public Domain)
#include "config.hpp"
#include <fstream>
namespace config
{
std::map<std::string, std::map<std::string, std::string>> tree{};
const std::string filePath{"config.ini"};
bool exists(const std::string& section, const std::string& name)
{
return tree.count(section) > 0 && tree[section].count(name) > 0;
}
void load()
{
tree.clear();
std::ifstream ifs{};
ifs.exceptions(std::ifstream::badbit);
ifs.open(filePath);
std::string line;
std::string section{};
while (std::getline(ifs, line))
{
if (line.empty() || line[0] == ';') continue;
if (line[0] == '[' && line[line.size() - 1] == ']')
{
section = line.substr(1, line.size() - 2);
continue;
}
auto delimiterPos = line.find_first_of('=');
if (delimiterPos != std::string::npos)
{
auto key = line.substr(0, delimiterPos);
auto value = line.substr(delimiterPos + 1, line.size() - delimiterPos);
tree[section][key] = value;
}
}
}
void save()
{
std::ofstream ofs{};
ofs.exceptions(std::ifstream::badbit);
ofs.open(filePath);
for (auto [section, property] : tree)
{
ofs << '[' << section << "]\n";
for (auto [key, value] : property)
{
ofs << key << '=' << value << '\n';
}
ofs << '\n';
}
ofs.close();
}
}
#pragma once
#include <map>
#include <string>
namespace config
{
extern std::map<std::string, std::map<std::string, std::string>> tree;
extern const std::string filePath;
void load();
void save();
bool exists(const std::string& section, const std::string& name);
template<typename T>
T set(const std::string& section, const std::string& name, T value)
{
std::ostringstream oss{};
oss << value;
tree[section][name] = oss.str();
return value;
}
template<typename T>
T get(const std::string& section, const std::string& name, T defaultValue = {})
{
if (!exists(section, name))
return set(section, name, defaultValue);
std::istringstream iss{tree[section][name]};
T ret;
iss >> ret;
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment