c++开发中如何读写yaml配置文件

2023-05-14 17:05:12 开发 读写 配置文件

c++ 开发中利用yaml-cpp读写yaml配置文件

1、yaml-cpp 是一个开源库,地址在 GitHub 上,https://github.com/jbeder/yaml-cpp。
ubuntu中可以输入git clone Https://github.com/jbeder/yaml-cpp获取yaml-cpp源码
2、进入到yaml-cpp目录,新建一个build目录。
3、进入到build目录,输入cmake -D BUILD_SHARED_LIBS=ON …编译出动态库。
4、创建自己测试用的文件夹,将yaml-cpp目录下面的include 目录拷贝到测试目录下,将编译后的动态库也拷贝到测试目录下,同事目录下在编写三个文件,分别为CMakeLists.txt、config.yaml、main.cpp。
main.cpp内容如下:

#include <iOStream>
#include "include/yaml-cpp/yaml.h"

using namespace std;

int main(int arGC,char** argv)
{
    YAML::node config = YAML::LoadFile("../config.yaml");

    cout << "name:" << config["name"].as<string>() << endl;
    cout << "sex:" << config["sex"].as<string>() << endl;
    cout << "age:" << config["age"].as<int>() << endl;
    return 0;
}

config.yaml内容如下:

name: xiaoyu
sex: man
age: 20

CMakeLists.txt内容如下:

cmake_minimum_required(VERSioN 3.2)

project(yaml_test)

add_definitions(-std=c++11)
include_directories(include)
set(SRCS main.cpp)
add_executable(yamltest ${SRCS})

target_link_libraries(yamltest ${CMAKE_HOME_DIRECTORY}/libs/libyaml-cpp.so)

5、在当前目录创建 build 文件夹,然后进入 build 文件执行 cmake 操作。

mkdir build
cd build
cmake ..

特别说明:
编译过程中如遇到:
关于 CMake Error: CMake Error: The source directory …does not appear to contain CMakeLists.txt.这个问题时,只需要复制一下终端报错内容中的CMakeLists.txt对自己所写的cmake文件重新命名,编译就可以啦。

到此这篇关于c++ 开发中读写yaml配置文件的文章就介绍到这了,更多相关c++ yaml配置文件内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章