安装yaml-cpp
git clone https://github.com/jbeder/yaml-cpp.git
cd yaml-cpp
mkdir build && cd build
cmake .. && make -j
sudo make install
CMakeLists配置
find_package(yaml-cpp REQUIRED)
include_directories(${YAML_CPP_INCLUDE_DIR})
# add_executable (main ${COMMON}) #连接编译编译路径
# 动态连接yaml库
target_link_libraries(main yaml-cpp::yaml-cpp)
Node是yaml-cpp中最重要的数据结构,Node一共有以下几种type
#include <iostream>
#include <fstream>
#include <yaml-cpp/yaml.h>
#include <iostream>
#include <assert.h>
int main()
{
YAML::Node node1;
assert(node1.IsNull()); //1. 初始化的节点是Null类型
node1["key"] = "value"; //2. 当你给它赋值键值对,它转变为Map类型
node1["number"] = 255;
assert(node1.IsMap());
node1["seq"].push_back("first element");//seq对应的是一个Sequence
node1["seq"].push_back("second element");
std::cout << node1 << std::endl;
/*输出结果:
key: value
number: 255
seq:
- first element
- second element
*/
node1.remove("key"); //删除
YAML::Node node2;
node2.push_back("first item");//3. 它是一个sequence类型
node2.push_back("second_item");
node2.push_back("third_item");
std::vector<int> v = {1,3,5,7,9};//给node_2插入了一个Sequence
node2.push_back(v);
assert(node2.IsSequence());//当然,node_2仍然是一个Sequence
for(auto it = node2.begin(); it != node2.end(); it++)
std::cout << *(it) << std::endl;
/*输出结果:
first item
second_item
third_item
- 1
- 3
- 5
- 7
- 9
*/
node2.remove(0);//删除first item
node2[0] = "new fir";
/*修改后
second_item
new fir
- 1
- 3
- 5
- 7
- 9
*/
}
用 loadFile() 可从文件生成Node
Node LoadFile(const std::string& filename)
//filename 就是yaml文件的路径
实战:
name: xiaoming
sex: male
age: 18
system:
port: 0
value: 0
int_vec: [10, 20]
#include "log.h"
#include <iostream>
#include <fstream>
#include <yaml-cpp/yaml.h>
#include <iostream>
#include <assert.h>
int main()
{
YAML::Node node = YAML::LoadFile("./test.yaml");
//获取类型
std::cout << node.Type() << std::endl; //4
std::cout << node["name"].Type() << std::endl;//2
//获取内容
std::cout << node["name"].as<std::string>() << std::endl;//xiaoming
std::cout << node["sex"].as<std::string>() << std::endl;//male
std::cout << node["age"].as<int>() << std::endl;//18
std::cout << node["system"]["port"].as<std::string>() << std::endl;//8080
std::cout << node["system"]["value"].as<std::string>() << std::endl;//0
for(auto it = node["system"]["int_vec"].begin(); it != node["system"]["int_vec"].end(); it++)
std::cout << *it << std::endl;//10 20
//方式2
for(auto it = node.begin(); it != node.end(); it++)//first指向key , second指向value
std::cout << it->first << " " << it->second << std::endl;
/*读取结果
name xiaoming
sex male
age 18
system port: 0
value: 0
int_vec: [10, 20]
*/
//读取不存在的node值,报YAML::TypedBadConversion异常
try{
std::string label = node["label"].as<std::string>();
}catch(YAML::TypedBadConversion<std::string> &e){
std::cout<<"label node is NULL"<<std::endl;
}
//修改
node["mg"] = 2;
//保存config为yaml文件
std::ofstream fout("./test.yaml");
fout << node;
fout.close();
return 0;
}
name: xiaoming
sex: male
age: 18
system:
port: 0
value: 0
int_vec: [10, 20]
mg: 2