> 文章列表 > c++ 开发中读写yaml配置文件

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

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

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文件重新命名,编译就可以啦。