在C++的项目中,我们可以选择使用哪种配置文件?选择配置文件的两个依据可能是:
具体可参考:Config Files: INI, XML, JSON, YAML, TOML
在C++中,Boost.PropertyTree是一个保存了多个属性值的树形数据结构, 它可以用类似路径的简单方式访问任意节点的属性,而且每个节点都可以用类似STL的风格遍历子节点。property_tree特别适用于应用程序的配置数据处理, 它可以解析XML、JSON、INI格式的文本数据,使用它能够减轻开发配置管理的工作。
但是XML、JSON、INI这三种格式,我都没选。INI比较简单,不够花里胡哨;JSON不能写注释;XML有些复杂。阅读Config Files: INI, XML, JSON, YAML, TOML后, 我选择toml-lang/toml作为配置文件格式。(INI可能是更好的选择。但好玩起见,尝试使用TOML)
见官方文档。
下面代码来自:da1234cao/FreeFile
配置文件如下所示,包含字符串,数组,表。
# TOML中的单引号是文字常量,不允许转义
# handle.exe文件路径
handle = '.\handle.exe'
# 被进程占用的文件路径
freeFiles = ['D:\cmake', 'E:\tmp.txt']
# 运行过程中生成内容路径
tmpfile = '.\output.txt'
# 日志文件
[log]
path = '.\freeFile.log'
level = 'trace'
max_file_size = 1 # MB单位
max_files = 3
接口使用如下。
# toml
FetchContent_Declare(
tomlplusplus
GIT_REPOSITORY https://github.com/marzer/tomlplusplus.git
GIT_TAG v3.1.0
GIT_SUBMODULES ""
)
FetchContent_MakeAvailable(tomlplusplus)
include_directories(${tomlplusplus_SOURCE_DIR}/include)
add_executable(${PROJECT_NAME} "main.cpp")
target_link_libraries(${PROJECT_NAME} PRIVATE tomlplusplus::tomlplusplus)
try {
// 从配置文件中提取信息
toml::table tlbs;
optional handle, tmpfile; // optional异常未捕获
set free_files;
string log_file_path, logger_name, log_level;
size_t max_log_file_size, max_log_files;
try {
tlbs = toml::parse_file(R"(.\config.toml)");
handle = tlbs["handle"].value();
tmpfile = tlbs["tmpfile"].value();
const toml::array &freeFiles = *tlbs.get_as("freeFiles");
for (int i = 0; i < freeFiles.size(); i++) {
free_files.insert(freeFiles[i].value().value());
}
log_file_path = tlbs["log"]["path"].value().value();
log_level = tlbs["log"]["level"].value().value();
max_log_file_size = tlbs["log"]["max_file_size"].value().value();
max_log_files = tlbs["log"]["max_files"].value().value();
} catch (const toml::parse_error& err) {
cerr << "Parsing failed:\n" << err << "\n";
return 1;
}
......