目录
1 安装yaml-cpp
2 工程结构
(1)test.yaml的内容
(2)CmakeLists.txt
(3)代码
3 运行结果
4 报错处理
1 安装yaml-cpp
(1)cd 到yaml-cpp下载的目的路径
例如:cd /home/test
(2)git clone https://github.com/jbeder/yaml-cpp
(3)cd yaml-cpp
(4)创建build文件夹
mkdir build
(5)cd build
(6)cmake .. -D BUILD_SHARED_LIBS=ON
说明: yaml-cpp 默认构建的是静态库,就是 .a 文件,如果想构建动态库,就需要在 cmake 时指定,如上。
(7)make
至此,就结束啦。
2 工程结构
(1)test.yaml的内容
name: Jack
sex: male
age: 22
code: 1102698
skills:
c++: 1
HTML: 1
(2)CmakeLists.txt
cmake_minimum_required(VERSION 3.22)
project(yaml_practice)
set(CMAKE_CXX_STANDARD 14)
include_directories("/home/test/yaml-cpp/include/")
add_executable(yaml_practice main.cpp)
target_link_libraries( yaml_practice /home/test/yaml-cpp/build/libyaml-cpp.so)
(3)代码
main.cpp
#include <iostream>
#include <string>
#include <fstream>
#include "yaml-cpp/yaml.h"
using namespace std;
void get_content(YAML::Node yamlTest)
{
for (YAML::const_iterator it = yamlTest.begin(); it != yamlTest.end(); it++)
{
if(it->second.size() == 0) {
cout << it->first.as<string>() << ": " << it->second << endl;
}
else{
YAML::Node value = it->second;
for(YAML::const_iterator id = value.begin(); id != value.end(); id++)
cout << it->first.as<string>() << ": " << id->first<< ": " << id->second << endl;
}
}
}
void add_content(string config_path){
YAML::Node yamlTest = YAML::LoadFile(config_path);
ofstream fout(config_path);
yamlTest["skills"]["python"] = 0;
fout << yamlTest;
fout.close();
get_content(yamlTest);
}
void delete_content(string config_path){
YAML::Node yamlTest = YAML::LoadFile(config_path);
ofstream fout(config_path);
yamlTest["skills"].remove("HTML");
fout << yamlTest;
fout.close();
get_content(yamlTest);
}
void edit_content(string config_path){
YAML::Node yamlTest = YAML::LoadFile(config_path);
ofstream fout(config_path);
yamlTest["code"] = 1102;
fout << yamlTest;
fout.close();
get_content(yamlTest);
}
int main(){
string config_path = "/home/test/CLionProjects/practice/test.yaml";
cout << "*** original content :" << endl;
YAML::Node yamlTest = YAML::LoadFile(config_path);
get_content(yamlTest);
cout << "*** add content : skills python" << endl;
add_content(config_path);
cout << "*** delete content : skills HTML" << endl;
delete_content(config_path);
cout << "*** edit content : code=1102" << endl;
edit_content(config_path);
return 0;
}
3 运行结果
4 报错处理
(1)erminate called after throwing an instance of 'YAML::BadFile'
what(): bad file: test.yaml
Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
解决方法:检查主函数中的yaml文件路径,建议使用绝对路径。
(2)terminate called after throwing an instance of 'YAML::ParserException' what(): yaml-cpp: error at line 6, column 5: illegal map value
解决方法:test.yaml中的内容要使用空格,不要用Tab键。