INIParser/INIParser.cpp

105 lines
2.0 KiB
C++

#include "INIParser.hpp"
#include <iostream>
#include <fstream>
#include <string>
INIParser::INIParser() { }
INIParser::INIParser(const std::string& filename) : m_file(filename) {
if (!m_file.is_open()) {
throw std::runtime_error("Couldn't open the file: " + filename);
}
}
void INIParser::parse() {
if (!m_file.is_open()) {
throw std::runtime_error("Error in constructor");
}
std::string line;
std::string section, key, value;
std::string buffer;
while (std::getline(m_file, line)) {
m_deleteSpace(line);
if (line.empty()) {
continue;
}
if (line[0] == '[' && line[line.size() - 1] == ']') {
section = line.substr(1, line.size() - 2);
m_sections[section] = {};
} else {
size_t separator = line.find('=');
if (separator != std::string::npos) {
buffer = line.substr(0, separator);
m_deleteSpace(buffer);
key = buffer;
buffer = line.substr(separator + 1);
m_deleteSpace(buffer);
value = buffer;
m_sections[section][key] = value;
}
}
}
m_file.clear();
m_file.seekg(0);
}
std::string INIParser::getValue(const std::string& section, const std::string& key) {
return m_sections[section][key];
}
std::string INIParser::getKey(const std::string& section) {
std::string keys;
if (m_sections.find(section) != m_sections.end()) {
for (const auto& pair : m_sections[section]) {
if (!keys.empty()) {
keys += '|';
}
keys += pair.first;
}
}
return keys;
}
std::string INIParser::getSection() {
std::string sectionList;
for (const auto& pair : m_sections) {
if (!sectionList.empty()) {
sectionList += '|';
}
sectionList += pair.first;
}
return sectionList;
}
void INIParser::m_deleteSpace(std::string& line) {
int length = line.length();
int index = 0;
for (int i = 0; i < length; i++) {
if (line[i] != ' ') {
line[index++] = line[i];
}
}
line.resize(index);
}
INIParser::~INIParser() {
if (!m_file.is_open()) {
throw std::runtime_error("Error in constructor");
} else {
m_file.close();
}
}