我们的程序无论运行在什么环境,很多都会用到配置文件,Windows环境有系统自带的SDK读写ini配置文件,而linux没有,本文分享一个arm linux环境下读写配置文件的类,利用libconfig封装而成,且是单实例类,ArmV7处理器可以直接用(gcc-linaro5.5.0编译的)。
#ifndef __CFG_SETTINGS_H__
#define __CFG_SETTINGS_H__
#include <mutex>
#include "libconfig.h"
class CfgSettings{
private:
static CfgSettings c_settings;
config_t c_config;
std::mutex c_mutex;
private:
void init();
public:
CfgSettings(/* args */);
~CfgSettings();
static Settings &getInstance();
// 打开配置文件
int open(const char *filename);
// 读指定的配置项
int read(std::string path, std::string &value);
//写指定配置项---string
int write(std::string path, std::string &value);
//写指定配置项---int
int write(std::string path, int &value);
int save(std::string fname);
/**/
void close();
};
#endif /* __CFG_SETTINGS_H__ */
#include "CfgSettings.h"
//类实例化
CfgSettings CfgCfgSettings::c_settings;
CfgSettings::CfgSettings(/* args */){
init();
}
CfgSettings::~CfgSettings(){
close();
}
CfgSettings &CfgSettings::getInstance(){
return c_settings;
}
void CfgSettings::init(){
config_init(&c_config);
}
int CfgSettings::open(const char *filename){
std::lock_guard<std::mutex> lock(c_mutex);
if(NULL == filename){
return -1;
}
if(-1 == access(filename, F_OK)){
return -1;
}
int ret = config_read_file(&c_config, filename);
if(!ret)
{
config_destroy(&c_config);
return ret;
}
return ret;
}
int CfgSettings::read(std::string path, std::string &value){
std::lock_guard<std::mutex> lock(c_mutex);
if(path.empty()){
return -1;
}
const char *v = NULL;
int ret = config_lookup_string(&c_config, (const char *)path.c_str(), &v);
if(ret){
value = v;
return 0;
} else {
return -1;
}
}
int CfgSettings::save(std::string fname){
if(fname.empty()){
return -1;
}
return config_write_file(&c_config, (const char *)fname.c_str());
}
int CfgSettings::write(std::string path, std::string &value){
std::lock_guard<std::mutex> lock(c_mutex);
if(path.empty()){
return -1;
}
config_setting_t *root = config_root_setting(&c_config);
config_setting_t *setting = config_setting_lookup(root, (const char *)path.c_str());
if(NULL == setting){
setting = config_setting_add(root, path.c_str(), CONFIG_TYPE_STRING);
}
return config_setting_set_string(setting, value.c_str());
}
int CfgSettings::write(std::string path, int &value){
std::lock_guard<std::mutex> lock(c_mutex);
if(path.empty()){
return -1;
}
config_setting_t *root = config_root_setting(&c_config);
config_setting_t *setting = config_setting_lookup(root, (const char *)path.c_str());
if(NULL == setting){
setting = config_setting_add(root, path.c_str(), CONFIG_TYPE_INT);
}
return config_setting_set_int(setting, value);
}
void CfgSettings::close(){
config_destroy(&c_config);
}
点击下载 全部代码和库 [包含封装类的代码libconfig.a和libconfig.h ]
本文介绍了一个在ARMLinux环境中,利用libconfig库实现的配置文件读写类,支持单例模式,适用于多种处理器,特别适合GCC-linaro5.5.0编译环境,提供文件操作和数据类型转换功能。
213

被折叠的 条评论
为什么被折叠?



