/* * parameterfile.cpp * * Created on: Jul 19, 2011 * Author: muecklgr_local */ #include #include #include #include #include "GLTB/exception.h" #include "GLTB/parameterfile.h" namespace gltb { ParameterFile::ParameterFile(std::string filename) { parseFile(filename.c_str()); } bool ParameterFile::getBool(std::string paramName, bool defaultValue) { if(paramMap.find(paramName)==paramMap.end()) return defaultValue; int helper=atoi(paramMap[paramName].c_str()); if(helper==0) { return false; } else { return true; } } void ParameterFile::setBool(std::string paramName, bool value) { if(value==true) { paramMap[paramName]="1"; } else { paramMap[paramName]="0"; } } int ParameterFile::getInt(std::string paramName, int defaultValue) { if(paramMap.find(paramName)==paramMap.end()) { return defaultValue; } return atoi(paramMap[paramName].c_str()); } void ParameterFile::setInt(std::string paramName, int value) { std::ostringstream temp; temp << value; paramMap[paramName]=temp.str(); } float ParameterFile::getFloat(std::string paramName, float defaultValue) { if(paramMap.find(paramName)==paramMap.end()) { return defaultValue; } return (float)atof(paramMap[paramName].c_str()); } void ParameterFile::setFloat(std::string paramName, float value) { std::ostringstream temp; temp << value; paramMap[paramName]=temp.str(); } std::string ParameterFile::getString(std::string paramName, std::string defaultValue) { if(paramMap.find(paramName)==paramMap.end()) { return defaultValue; } return paramMap[paramName]; } void ParameterFile::setString(std::string paramName, std::string value) { paramMap[paramName]=value; } void ParameterFile::parseFile(const char *filename) { char helper[128]; std::ifstream config(filename); if(!config) { throw Exception("cannot read file " + std::string(filename),"ParameterFile::parseFile()"); } // parse file while(!config.eof()) { config.getline(helper,128); std::string line=helper; // cut off comments: line=line.substr(0,line.find_first_of("#")); // cut off leading blank characters: while(line.length()>0 && isspace(line[0])) { line=line.substr(1,line.length()-1); } // cut off trailing blank characters: while(line.length()>0 && isspace(line[line.length()-1])) { line=line.substr(0,line.length()-1); } if(line=="") continue; // skip blank lines std::string param=line.substr(0,line.find_first_of("=")); std::string value=line.substr(param.length()+1,line.length()-param.length()-1); paramMap[param]=value; } } void ParameterFile::saveFile(std::string filename) { std::ofstream file(filename.c_str()); std::map::iterator mi; if(!file) { // we don't bother much if we can't save the configuration return; } for(mi=paramMap.begin();mi!=paramMap.end();++mi) { file << mi->first << "=" << mi->second << std::endl; } } }