1. yaml-cpp安装
- yaml-cpp开源库,github地址,其通过CMake进行编译构建,步骤如下:
mkdir build // 新建build文件夹
cd build
cmake -DBUILD_SHARED_LIBS=ON ..
// 构建上层目录的CMakeLists.txt,编译文件放在build文件夹内
make
sudo make install
ubuntu16.04安装yaml:
sudo apt-get install libyaml-cpp-dev
我的应该是安装其他软件包时依赖所以已经安装了,目录在/usr/include/yaml-cpp
,以*.h形式存在。
2. read yaml
#ifdef HAVE_NEW_YAMLCPP
// The >> operator disappeared in yaml-cpp 0.5, so this function is
// added to provide support for code written under the yaml-cpp 0.3 API.
template<typename T>
void operator >> (const YAML::Node& node, T& i)
{
i = node.as<T>();
}
#endif
void loadYamlFile(std::string name){
YAML::Node node = YAML::LoadFile(name);
std::string test_param2;
node["marker_name"] >> test_param2;
std::cout << test_param2 << std::endl;
}
// CMakeLists.txt
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -O3 -Wall")
add_definitions(-std=c++11)
INCLUDE(FindPkgConfig)
pkg_check_modules(NEW_YAMLCPP yaml-cpp>=0.5)
if(NEW_YAMLCPP_FOUND)
add_definitions(-DHAVE_NEW_YAMLCPP)
endif(NEW_YAMLCPP_FOUND)
test.yaml: marker_name: t_1
直接调用loadYamlFile(marker_file);
,打印test_param2结果t_1
。
3. write yaml
std::ofstream out(marker_file, std::ios::app);
std::string marker_name = "t_" + std::to_string(cnt);
std::cout << "marker_name :" << marker_name << std::endl;
Emitter node;
node << BeginMap;
node << Key << "marker_name" << Value << marker_name;
node << Key << "pose" << Value << msg->pose;
node << Key << "---";
node << EndMap;
out << node.c_str();
out << '\n';
out.close();
cnt++;
std::cout << "------------------" << std::endl;
yaml结果:
marker_name: t_1
pose:
position: [-0.107327938079834, 0.3301165103912354, 0]
orientation: [0, 0, 0.642, 0.766]
---
marker_name: t_2
pose:
position: [-1.01, -0.475, 0]
orientation: [0, 0, 0.868, -0.497]
---