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"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM