#include #include #include #include #include "parser.h" namespace config { parser::parser() { } parser::parser(const char *filename) : m_filename(filename) { read_file(); } parser::~parser() { write_file(); } void parser::read_file() { std::ifstream ifile(m_filename.c_str()); std::string line; std::string section; while (std::getline(ifile, line)) { if (line.size() > 0) { // Line is a comment if (line.at(0) == '#') continue; // Line is a section if (line.at(0) == '[' && line.at(line.size() - 1) == ']') { section = line.substr(1, line.size() - 2); boost::trim(section); continue; } // line is a pair key = value int pos = line.find_first_of("="); if (pos != std::string::npos) { // No previous section defined if (section.size() == 0) throw std::logic_error("No section in config file"); std::string left_string = line.substr(0, pos); std::string right_string = line.substr(pos + 1); boost::trim(left_string); boost::trim(right_string); m_map[section][left_string] = right_string; } } } ifile.close(); } void parser::write_file() { if (m_map.size() > 0) { std::ofstream file(m_filename.c_str()); for (section_map::iterator it = m_map.begin(); it != m_map.end(); ++it) { file << "[" << it->first << "]" << std::endl; for (key_map::iterator iter = it->second.begin(); iter != it->second.end(); ++iter) file << iter->first << " = " << iter->second << std::endl; } file.close(); } } std::string parser::get(const std::string & section, const std::string & key) { return m_map[section][key]; } void parser::set(const std::string & section, const std::string & key, const std::string & value) { m_map[section][key] = value; } template void parser::test() {} } // namespace config