yaml作为一种便捷的文件格式,通过c++进行操作时,可以利用yaml-cpp进行。
一,yaml-cpp的安装
下载源码
git clone https://github.com/jbeder/yaml-cpp.git
编译安装
mkdir build
cd build
cmake -DBUILD_SHARED_LIBS=ON .. # ON 设置生成共享库
sudo make install
验证
pkg-config --modversion yaml-cpp
使用
YAML::Node node1 = YAML::LoadFile("config.yaml"); // 加载文件
YAML::Node node2 = YAML::Load("[1,2,3]"); // 加载数组
cout << node1[0].as<string>() << endl; cout << node2[0].as<int>() << endl; // 输出元素
更多API参考yaml-cpp docs。
示例:
a、CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(yaml_test)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") link_directories(/home/jonty/Softwares/yaml-cpp/build) include_directories(/home/jonty/Softwares/yaml-cpp/include/yaml-cpp) add_executable(test main.cpp) target_link_libraries(test yaml-cpp)
b、main.cpp
#include <iostream>
#include "yaml.h" using namespace std; int main() { YAML::Node node = YAML::Load("[22,3,4,4]"); cout << node[0] << endl; YAML::Node node2 = YAML::LoadFile("../config.yaml"); cout << node2["ttt"] << endl; return 0; }
编译运行
mkdir build
cd build
cmake ..
make
./test
参考教程https://github.com/jbeder/yaml-cpp/wiki/Tutorial
编译也可以采用g++ test.cpp /usr/local/lib/libyaml-cpp.a -std=c++11
源码编译yaml-cpp
git clone https://github.com/jbeder/yaml-cpp.git
cd yaml-cpp # 进入克隆的文件夹
mkdir build
cd build
cmake ..
make
make install
可参考https://blog.csdn.net/Fourier_Legend/article/details/82798297