c++读取properties/conf配置文件
1. libConfuse介绍
libconfuse 是一个用C实现配置文件解析器库,授权的ISC许可的条件下,它支持段(列表)和值(字符串,整数,浮点数,布尔值或其他部分),以及一些其他功能(如单/双引号字符串,环境变量扩展,功能嵌套include语句)。它可以添加配置文件的能力,使用简单的API使程序读取配置文件非常容易。
详细的介绍请访问:http://www.nongnu.org/confuse/,代码托管在github:https://github.com/martinh/libconfuse
我们可以使用libconfuse库来实现c++从配置文件中读取参数。
2. 安装
详细介绍可见:https://github.com/martinh/libconfuse
安装步骤:
1 wget https://github.com/martinh/libconfuse/releases/download/v3.2/confuse-3.2.tar.gz 2 ./configure 3 make 4 sudo make install
3. 使用
详细介绍可见:http://www.nongnu.org/confuse/tutorial-html/index.html
CMakeLists.txt
cmake_minimum_required(VERSION 3.12) project(properties) set(CMAKE_CXX_STANDARD 14) add_executable(properties main.cpp) target_link_libraries(properties confuse)
main.cpp
#include <stdio.h>
#include <confuse.h>
int main(void) {
cfg_opt_t opts[] =
{
CFG_STR("target", "World", CFGF_NONE), //设置默认值
CFG_INT("num", -1, CFGF_NONE),
CFG_END()
};
cfg_t *cfg;
cfg = cfg_init(opts, CFGF_NONE);
if (cfg_parse(cfg, "../stuff.conf") == CFG_PARSE_ERROR) {
printf("parse file failed!\n");
return 1;
}
printf("Hello, %s!\n", cfg_getstr(cfg, "target"));
printf("num is %d!\n",(int)cfg_getint(cfg,"num"));
cfg_free(cfg);
return 0;
}
stuff.properties
num = 9
target= "zjp"