|
| 1 | +// Read an INI file into easy-to-access name/value pairs. |
| 2 | + |
| 3 | +#include <algorithm> |
| 4 | +#include <cctype> |
| 5 | +#include <cstdlib> |
| 6 | +#include "../ini.h" |
| 7 | +#include "INIReader.h" |
| 8 | + |
| 9 | +using std::string; |
| 10 | + |
| 11 | +INIReader::INIReader(string filename) |
| 12 | +{ |
| 13 | + _error = ini_parse(filename.c_str(), ValueHandler, this); |
| 14 | +} |
| 15 | + |
| 16 | +int INIReader::ParseError() |
| 17 | +{ |
| 18 | + return _error; |
| 19 | +} |
| 20 | + |
| 21 | +string INIReader::Get(string section, string name, string default_value) |
| 22 | +{ |
| 23 | + string key = MakeKey(section, name); |
| 24 | + return _values.count(key) ? _values[key] : default_value; |
| 25 | +} |
| 26 | + |
| 27 | +long INIReader::GetInteger(string section, string name, long default_value) |
| 28 | +{ |
| 29 | + string valstr = Get(section, name, ""); |
| 30 | + const char* value = valstr.c_str(); |
| 31 | + char* end; |
| 32 | + // This parses "1234" (decimal) and also "0x4D2" (hex) |
| 33 | + long n = strtol(value, &end, 0); |
| 34 | + return end > value ? n : default_value; |
| 35 | +} |
| 36 | + |
| 37 | +bool INIReader::GetBoolean(string section, string name, bool default_value) |
| 38 | +{ |
| 39 | + string valstr = Get(section, name, ""); |
| 40 | + // Convert to lower case to make string comparisons case-insensitive |
| 41 | + std::transform(valstr.begin(), valstr.end(), valstr.begin(), ::tolower); |
| 42 | + if (valstr == "true" || valstr == "yes" || valstr == "on" || valstr == "1") |
| 43 | + return true; |
| 44 | + else if (valstr == "false" || valstr == "no" || valstr == "off" || valstr == "0") |
| 45 | + return false; |
| 46 | + else |
| 47 | + return default_value; |
| 48 | +} |
| 49 | + |
| 50 | +string INIReader::MakeKey(string section, string name) |
| 51 | +{ |
| 52 | + string key = section + "." + name; |
| 53 | + // Convert to lower case to make section/name lookups case-insensitive |
| 54 | + std::transform(key.begin(), key.end(), key.begin(), ::tolower); |
| 55 | + return key; |
| 56 | +} |
| 57 | + |
| 58 | +int INIReader::ValueHandler(void* user, const char* section, const char* name, |
| 59 | + const char* value) |
| 60 | +{ |
| 61 | + INIReader* reader = (INIReader*)user; |
| 62 | + string key = MakeKey(section, name); |
| 63 | + if (reader->_values[key].size() > 0) |
| 64 | + reader->_values[key] += "\n"; |
| 65 | + reader->_values[key] += value; |
| 66 | + return 1; |
| 67 | +} |
0 commit comments