#include "common/pch.h" #include "ConfigUtil.h" #include #include #include "../common/JsonUtil.h" bool fileExists(const std::string& filename) { std::ifstream file(filename); return file.good(); // Èç¹ûÎļþ³É¹¦´ò¿ª£¬Ôò·µ»Ø true } void ConfigUtil::readConfig(libconfig::Config& config) { string strConfPath = "config.cfg"; if (!fileExists(strConfPath)) { std::ofstream file(strConfPath); file.is_open(); } //½â¶ÁÅäÖÃÎļþ try { config.readFile(strConfPath.c_str()); } catch (const libconfig::FileIOException& fioex) { std::cerr << "I/O exception while reading the file." << std::endl; } catch (const libconfig::ParseException& pex) { std::cerr << "Parse error at " << pex.getFile() << ":" << pex.getLine() << " - " << pex.getError() << std::endl; } } void ConfigUtil::writeConfig(libconfig::Config& config) { config.writeFile("config.cfg"); } int ConfigUtil::readIntConfig(const char* key) { libconfig::Config mConfig; readConfig(mConfig); libconfig::Setting& root = mConfig.getRoot(); if (root.exists(key)) { int val; root.lookupValue(key, val); return val; } throw string("ÉÐδ»ñÈ¡µ½ÄÚÈÝ"); } string ConfigUtil::readStringConfig(const char* key) { libconfig::Config mConfig; readConfig(mConfig); libconfig::Setting& root = mConfig.getRoot(); if (root.exists(key)) { //string val; const char* val; root.lookupValue(key, val); return string(val); } throw string("ÉÐδ»ñÈ¡µ½ÄÚÈÝ"); } void ConfigUtil::setIntConfig(const char* key, int val) { libconfig::Config mConfig; readConfig(mConfig); libconfig::Setting& root = mConfig.getRoot(); if (root.exists(key)) { root[key] = val; } else { root.add(key, libconfig::Setting::TypeInt) = val; } writeConfig(mConfig); } void ConfigUtil::setStringConfig(const char* key, string val) { libconfig::Config mConfig; readConfig(mConfig); libconfig::Setting& root = mConfig.getRoot(); if (root.exists(key)) { root[key] = val.c_str(); } else { root.add(key, libconfig::Setting::TypeString) = val.c_str(); } writeConfig(mConfig); } POINT ConfigUtil::getWindowPos() { // Ò³ÂëλÖà try { string data = readStringConfig("window_pos"); rapidjson::Document root = JsonUtil::parseUTF8(data); return POINT({ root[0].GetInt(), root[1].GetInt() }); } catch (...) { } return POINT({ 0,0 }); } void ConfigUtil::setWindowPos(int x, int y) { string st = "["; st.append(std::to_string(x)).append(",").append(std::to_string(y)).append("]"); setStringConfig("window_pos", st); }