78 lines
2.1 KiB
C++
78 lines
2.1 KiB
C++
#include "Config/Common/IniParser.h"
|
|
#include <fstream>
|
|
#include <sstream>
|
|
#include <algorithm>
|
|
|
|
namespace config
|
|
{
|
|
std::string trim(std::string s)
|
|
{
|
|
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int c)
|
|
{ return !isspace(c); }));
|
|
s.erase(std::find_if(s.rbegin(), s.rend(), [](int c)
|
|
{ return !isspace(c); })
|
|
.base(),
|
|
s.end());
|
|
return s;
|
|
}
|
|
|
|
std::vector<std::string> splitList(const std::string &s, char delim)
|
|
{
|
|
std::vector<std::string> result;
|
|
std::string item;
|
|
std::istringstream ss(s);
|
|
|
|
while (std::getline(ss, item, delim))
|
|
{
|
|
item = trim(item);
|
|
if (!item.empty())
|
|
result.push_back(item);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
bool IniParser::load(const std::string &path)
|
|
{
|
|
std::ifstream f(path);
|
|
if (!f)
|
|
return false;
|
|
|
|
std::string line, section;
|
|
while (std::getline(f, line))
|
|
{
|
|
line = trim(line);
|
|
if (line.empty() || line[0] == '#' || line[0] == ';')
|
|
continue;
|
|
|
|
if (line.front() == '[' && line.back() == ']')
|
|
{
|
|
section = line.substr(1, line.size() - 2);
|
|
continue;
|
|
}
|
|
|
|
auto pos = line.find('=');
|
|
if (pos == std::string::npos)
|
|
continue;
|
|
|
|
std::string key = trim(line.substr(0, pos));
|
|
std::string val = trim(line.substr(pos + 1));
|
|
data[section][key] = val;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
std::string IniParser::get(const std::string §ion,
|
|
const std::string &key,
|
|
const std::string &def) const
|
|
{
|
|
auto s = data.find(section);
|
|
if (s == data.end())
|
|
return def;
|
|
auto k = s->second.find(key);
|
|
if (k == s->second.end())
|
|
return def;
|
|
return k->second;
|
|
}
|
|
} // namespace config
|