38 #include "lcf/inireader.h"
42 INIReader::INIReader(
const std::string& filename)
44 _error = ini_parse(filename.c_str(), ValueHandler,
this);
47 INIReader::INIReader(std::istream& filestream)
49 _error = ini_parse_stream([](
char* str,
int num,
void* stream) {
50 std::istream* is =
reinterpret_cast<std::istream*
>(stream);
55 std::istream::sentry se(*is,
true);
56 std::streambuf* sb = is->rdbuf();
67 if (sb->sgetc() ==
'\n') {
75 is->setstate(std::ios::eofbit);
84 if (out.empty() && (is->fail() || is->eof())) {
85 return (
char*)
nullptr;
88 strncpy(str, out.c_str(), num);
94 return (
char*)
nullptr;
95 }, &filestream, ValueHandler,
this);
98 int INIReader::ParseError()
const
103 std::string INIReader::Get(
const std::string& section,
const std::string& name,
const std::string& default_value)
const
105 std::string key = MakeKey(section, name);
107 return _values.count(key) ? _values.find(key)->second : default_value;
110 std::string INIReader::GetString(
const std::string& section,
const std::string& name,
const std::string& default_value)
const
112 const std::string str = Get(section, name,
"");
113 return str.empty() ? default_value : str;
116 long INIReader::GetInteger(
const std::string& section,
const std::string& name,
long default_value)
const
118 std::string valstr = Get(section, name,
"");
119 const char* value = valstr.c_str();
122 long n = strtol(value, &end, 0);
123 return end > value ? n : default_value;
126 double INIReader::GetReal(
const std::string& section,
const std::string& name,
double default_value)
const
128 std::string valstr = Get(section, name,
"");
129 const char* value = valstr.c_str();
131 double n = strtod(value, &end);
132 return end > value ? n : default_value;
135 bool INIReader::GetBoolean(
const std::string& section,
const std::string& name,
bool default_value)
const
137 std::string valstr = Get(section, name,
"");
139 std::transform(valstr.begin(), valstr.end(), valstr.begin(), ::tolower);
140 if (valstr ==
"true" || valstr ==
"yes" || valstr ==
"on" || valstr ==
"1")
142 else if (valstr ==
"false" || valstr ==
"no" || valstr ==
"off" || valstr ==
"0")
145 return default_value;
148 bool INIReader::HasValue(
const std::string& section,
const std::string& name)
const
150 std::string key = MakeKey(section, name);
151 return _values.count(key);
154 std::string INIReader::MakeKey(
const std::string& section,
const std::string& name)
156 std::string key = section +
"=" + name;
158 std::transform(key.begin(), key.end(), key.begin(), ::tolower);
162 int INIReader::ValueHandler(
void* user,
const char* section,
const char* name,
165 INIReader* reader =
static_cast<INIReader*
>(user);
166 std::string key = MakeKey(section, name);
167 if (reader->_values[key].size() > 0)
168 reader->_values[key] +=
"\n";
169 reader->_values[key] += value;