|
| 1 | +#include "ConfigFile.h" |
| 2 | + |
| 3 | +#include <fstream> |
| 4 | + |
| 5 | +std::string trim(std::string const& source, char const* delims = " \t\r\n") { |
| 6 | + std::string result(source); |
| 7 | + std::string::size_type index = result.find_last_not_of(delims); |
| 8 | + if(index != std::string::npos) |
| 9 | + result.erase(++index); |
| 10 | + |
| 11 | + index = result.find_first_not_of(delims); |
| 12 | + if(index != std::string::npos) |
| 13 | + result.erase(0, index); |
| 14 | + else |
| 15 | + result.erase(); |
| 16 | + return result; |
| 17 | +} |
| 18 | + |
| 19 | +ConfigFile::ConfigFile(std::string const& configFile) { |
| 20 | + std::ifstream file(configFile.c_str()); |
| 21 | + |
| 22 | + std::string line; |
| 23 | + std::string name; |
| 24 | + std::string value; |
| 25 | + std::string inSection; |
| 26 | + int posEqual; |
| 27 | + while (std::getline(file,line)) { |
| 28 | + |
| 29 | + if (! line.length()) continue; |
| 30 | + |
| 31 | + if (line[0] == '#') continue; |
| 32 | + if (line[0] == ';') continue; |
| 33 | + |
| 34 | + if (line[0] == '[') { |
| 35 | + inSection=trim(line.substr(1,line.find(']')-1)); |
| 36 | + continue; |
| 37 | + } |
| 38 | + |
| 39 | + posEqual=line.find('='); |
| 40 | + name = trim(line.substr(0,posEqual)); |
| 41 | + value = trim(line.substr(posEqual+1)); |
| 42 | + |
| 43 | + content_[inSection+'/'+name]=Chameleon(value); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +Chameleon const& ConfigFile::Value(std::string const& section, std::string const& entry) const { |
| 48 | + |
| 49 | + std::map<std::string,Chameleon>::const_iterator ci = content_.find(section + '/' + entry); |
| 50 | + |
| 51 | + if (ci == content_.end()) throw "does not exist"; |
| 52 | + |
| 53 | + return ci->second; |
| 54 | +} |
| 55 | + |
| 56 | +Chameleon const& ConfigFile::Value(std::string const& section, std::string const& entry, double value) { |
| 57 | + try { |
| 58 | + return Value(section, entry); |
| 59 | + } catch(const char *) { |
| 60 | + return content_.insert(std::make_pair(section+'/'+entry, Chameleon(value))).first->second; |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +Chameleon const& ConfigFile::Value(std::string const& section, std::string const& entry, std::string const& value) { |
| 65 | + try { |
| 66 | + return Value(section, entry); |
| 67 | + } catch(const char *) { |
| 68 | + return content_.insert(std::make_pair(section+'/'+entry, Chameleon(value))).first->second; |
| 69 | + } |
| 70 | +} |
0 commit comments