From f56a38083c7e2c4a5f6c333197a3753a642e258d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Atle=20Hellvik=20Havs=C3=B8?= Date: Sun, 28 Nov 2010 13:19:46 +0100 Subject: Added a Config class. Example usage: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Config hei; hei.add_element("nick", n); hei.add_element("server", s); hei.add_element("port", p); hei.get_element("nick"); hei.get_element("server"); hei.get_element("port"); Signed-off-by: Atle Hellvik Havsø --- common/config.cpp | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 common/config.cpp (limited to 'common/config.cpp') diff --git a/common/config.cpp b/common/config.cpp new file mode 100644 index 0000000..1649e23 --- /dev/null +++ b/common/config.cpp @@ -0,0 +1,81 @@ +#include "config.h" + +#include +#include +#include + +Config::Config() { + path = "aotenjou.conf"; + load_conf(); +} + +Config::Config(std::string path) { + path = path; + load_conf(); +} + +Config::~Config() { + save_conf(); +} + +/* + Adds a config-element to the list + */ +void Config::add_element(std::string keyword, std::string value) { + config[keyword] = value; +} + +void Config::add_element(std::string keyword, int value) { + std::stringstream out; + out << value; + config[keyword] = out.str(); +} + +/* +Load a value from the config. + */ +std::string Config::get_element(std::string keyword) { + return config[keyword]; +} + +/* + Initializes and loads the config from disk if it exists + */ +void Config::load_conf(){ + + std::ifstream config_file(path.c_str()); + + if(config_file.is_open()) { + while(config_file.good()) { + std::string config_line; + std::getline(config_file, config_line); + std::string id = config_line.substr(0, config_line.find("=") - 1); + std::string value = config_line.substr(config_line.find("=") + 2, config_line.length()-1); + config[id] = value; + } + + config_file.close(); + + } else { + std::cerr << "Unable to open configuration file..." << std::endl; + } +} + +/* + Saves the current config to disk + */ +void Config::save_conf(){ + + std::ofstream config_file(path.c_str(), std::ios::out | std::ios::trunc); + + if(config_file.is_open()) { + for(std::map::iterator it = config.begin(); it != config.end(); ++it) { + config_file << it->first << " = " << it->second << std::endl; + } + + config_file.close(); + } else { + std::cerr << "Unable to save to configuration file..." << std::endl; + } +} + -- cgit v1.2.3