#include "ConfigUtil.h"
|
|
#include "ConfigUtil.h"
|
#include <iostream>
|
#include <fstream>
|
|
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);
|
}
|
|
list<string> ConfigUtil::getKeys()
|
{
|
libconfig::Config mConfig;
|
readConfig(mConfig);
|
libconfig::Setting& root = mConfig.getRoot();
|
list<string> keys;
|
for (auto iter = root.begin(); iter != root.end(); ++iter) {
|
keys.push_back(iter->getName());
|
}
|
return keys;
|
}
|
|
void ConfigUtil::delKey(string key)
|
{
|
libconfig::Config mConfig;
|
readConfig(mConfig);
|
libconfig::Setting& root = mConfig.getRoot();
|
root.remove(key);
|
}
|