#include "Config.h" const string Config::SCREEN_WIDTH_KEY("screen_width"); const string Config::SCREEN_HEIGHT_KEY("screen_height"); const string Config::FULLSCREEN_KEY("fullscreen"); const string Config::SCREEN_WIDTH_DEFAULT("800"); const string Config::SCREEN_HEIGHT_DEFAULT("600"); const string Config::FULLSCREEN_DEFAULT("false"); Config::Config(const string& filename) :_screenWidth(0), _screenHeight(0) { ifstream inStream(filename.c_str(), fstream::in); map readValues; map unfoundValues; readFile(inStream, readValues); fillValues(readValues, unfoundValues); inStream.close(); ofstream outStream(filename.c_str(), fstream::app); writeUnfoundValues(outStream, unfoundValues); outStream.close(); } unsigned int Config::screenWidth() const { return _screenWidth; } unsigned int Config::screenHeight() const { return _screenHeight; } bool Config::fullscreen() const { return _fullscreen; } void Config::readFile(ifstream& file, map& map) { if (!file.is_open()) return; string nextEntry; while(!file.eof()) { file >> nextEntry; string::size_type equalsIndex = nextEntry.find("=",0); if (equalsIndex!=string::npos) { string key = nextEntry.substr(0,equalsIndex); string value = nextEntry.substr(equalsIndex+1); map[key] = value; } } } void Config::fillValues(const map& readValues, map& unfoundValues) { setScreenWidth(extractValue(readValues, unfoundValues, SCREEN_WIDTH_KEY, SCREEN_WIDTH_DEFAULT)); setScreenHeight(extractValue(readValues, unfoundValues, SCREEN_HEIGHT_KEY, SCREEN_HEIGHT_DEFAULT)); setFullscreen(extractValue(readValues, unfoundValues, FULLSCREEN_KEY, FULLSCREEN_DEFAULT)); } string Config::extractValue(const map& readValues, map& unfoundValues, const string& key, const string& defaultValue) { map::const_iterator findIter = readValues.find(key); if (findIter != readValues.end()) { return findIter->second; } else { unfoundValues[key] = defaultValue; return defaultValue; } } void Config::writeUnfoundValues(ofstream& file, const map& unfoundValues) { for (map::const_iterator iter = unfoundValues.begin(); iter!=unfoundValues.end(); ++iter) { file << iter->first << "=" << iter->second << endl; } } void Config::setScreenWidth(const string& screenWidthStr) { _screenWidth = atoi(screenWidthStr.c_str()); } void Config::setScreenHeight(const string& screenHeightStr) { _screenHeight = atoi(screenHeightStr.c_str()); } void Config::setFullscreen(const string& fullscreenStr) { _fullscreen = fullscreenStr=="true"; }