YAML-CPP
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
记得在CMakeLists.txt中加入
link_directories(/usr/local/lib)
include_directories(/usr/local/include/yaml-cpp)
以及在链接库target_link_libraries时,加上yaml-cpp。
void write_robot_status_to_yaml(string path, const string &filename,
double x, double y, double th)
{
//dir_file_exists(path, true);
dir_file_exists(path, false, true, filename.c_str());
std::ofstream yaml_file(path + filename, std::ios::out | std::ios::binary);
{
YAML::Emitter out(yaml_file);
out << YAML::BeginMap;
// TODO(whess): Use basename only?
out << YAML::Key << "x";
out << YAML::Value << x;
out << YAML::Key << "y";
out << YAML::Value << y;
out << YAML::Key << "th";
out << YAML::Value << th;
out << YAML::EndMap;
} yaml_file.close();
}
bool read_robot_status_from_yaml(string file_path, const string &file_name, double &x,
double &y, double &th)
{
if (!dir_file_exists(file_path, false, true, file_name.c_str()))
return false;
std::ifstream yaml_file(file_path + file_name, std::ios::out | std::ios::binary);
{
YAML::Node doc = YAML::Load(yaml_file); doc["x"] >> x;
doc["y"] >> y;
doc["th"] >> th;
}
yaml_file.close(); return true;
}
/*
* @brief 创建文件夹
*/
bool dir_file_exists(string dir, bool mkdir_flag, bool touchfile_flag, string filename)
{
char des_dir[];
str_2_char(dir, des_dir);
int state = access(des_dir, R_OK | W_OK);//#include<unistd.h>
if(state == )
{
ROS_INFO("state == 0");
return true;
}
else if(mkdir_flag)
{
dir = "mkdir " + dir;
str_2_char(dir, des_dir);
if(system(des_dir))
{
printf("generate dir %s successfully.",dir.c_str());
ROS_INFO("generate dir %s successfully.",dir.c_str());
//Basic_Info("generate dir {} successfully.",dir.c_str());
}
else
{
printf("generate dir %s fail.",dir.c_str());
ROS_INFO("generate dir %s fail.",dir.c_str());
//Basic_Info("generate dir {} fail.",dir.c_str());
}
return true;
}
else if(touchfile_flag)
{
dir = "touch " + dir + "/" + filename;
ROS_INFO("dir is %s", dir.c_str());
str_2_char(dir, des_dir);
if(system(des_dir))
{
printf("generate filename %s successfully.",dir.c_str());
ROS_INFO("generate filename %s successfully.",dir.c_str());
//Basic_Info("generate filename {} successfully.",dir.c_str());
}
else
{
printf("generate filename %s fail.",dir.c_str());
ROS_INFO("generate filename %s fail.",dir.c_str());
//Basic_Info("generate filename {} fail.",dir.c_str());
}
return true;
}
return false;
}
template <typename T>
void operator>>(const YAML::Node& node, T& i); template <typename T>
void operator>>(const YAML::Node& node, T& i) {
i = node.as<T>();
};
写个模板类加载参数
template<typename T>
T getParam(const string& name,const T& defaultValue) //This name must be namespace+parameter_name
{
T v;
if(ros::param::get(name,v)) //get parameter by name depend on ROS.
{
ROS_INFO_STREAM("Found parameter: "<<name<<",\tvalue: "<<v);
return v;
}
else
ROS_WARN_STREAM("Cannot find value for parameter: "<<name<<",\tassigning default: "<<defaultValue);
return defaultValue; //if the parameter haven't been set,it's value will return defaultValue.
}
在ROS系统中,参数读写一般通过xml或者yaml格式的文件,其中yaml用得比较多。这是一种可读性高,轻量级的标记语言,简单好用。
对于yaml文件,ros中用的较早版本的yaml-cpp库,最新的可在github上下载,并按照readme中所述的方法编译安装。
特别留意的是,如果需要生成共享库,cmake的时候后面一定要加上 -DBUILD_SHARED_LIBS=ON 这句话。
有了yaml库,在CMakeLists.txt中加入,
link_directories(/usr/local/lib)
include_directories(/usr/local/include/yaml-cpp)
最后别忘了在链接库target_link_libraries时,加上yaml-cpp。
关于库的使用,github上有一些简单的tutorial教程。
以下是简单的yaml文件读写操作示例。
#include <ros/ros.h>
#include <yaml-cpp/yaml.h>
#include <iostream>
#include <fstream> int main(int argc, char **argv)
{
std::string fin = "/home/user/param/param.yaml"; //yaml文件所在的路径
YAML::Node yamlConfig = YAML::LoadFile(fin);
int int_param = yamlConfig["int_param"].as<int>();
std::cout << " node size: " << yamlConfig.size() << std::endl;
std::cout << yamlConfig["bool_param"].as<bool>() << "\n";
yamlConfig["bool_param"] = !yamlConfig["bool_param"].as<bool>();
yamlConfig["str_param"] = "test";
std::ofstream file;
file.open(fin);
file.flush();
file << yamlConfig;
file.close(); return ;
}
其中,yaml文件里的内容为:
bool_param: true
int_param: 2
double_param: 0.5
str_param: "123"
也可采用Emit来生成yaml文件,代码如下:
#include <ros/ros.h>
#include <yaml-cpp/yaml.h>
#include <iostream>
#include <fstream> int main(int argc, char **argv)
{
std::ofstream fout("/home/user/param/param.yaml");
YAML::Emitter out(fout);
out << YAML::BeginMap;
out << YAML::Key << "int_param";
out << YAML::Value << ;
out << YAML::Key << "double_param";
out << YAML::Value << 0.5;
out << YAML::Key << "bool_param";
out << YAML::Value << false;
out << YAML::Comment("bool parameter");
out << YAML::Key << "str_param";
out << YAML::Value << "test";
out << YAML::EndMap; return ;
}
yml文件的其他操作可参见博文《.yaml参数文件的编写和使用》,
其综合运用的案例可参见博文:ros-opencv-qt-yaml综合运用之滤波。
YAML-CPP的更多相关文章
- c++ 解析yaml文件
		
一直用c++操作ini做配置文件,想换成yaml,在全球最大的同性交友网站github上搜索,看有没有开源的库,功夫不负有心人,找到了yaml-cpp,用他解析了一个yaml的例子非常好使,分享一下如 ...
 - C#与yaml解析
		
YAML 官方网站称 YAML 是"一种所有编程语言可用的友好的数据序列化标准".YAML Ain't Markup Language,和GNU一样,YAML是一个递归着说&quo ...
 - 使用“Cocos引擎”创建的cpp工程如何在VS中调试Cocos2d-x源码
		
前段时间Cocos2d-x更新了一个Cocos引擎,这是一个集合源码,IDE,Studio这一家老小的整合包,我们可以使用这个Cocos引擎来创建我们的项目. 在Cocos2d-x被整合到Cocos引 ...
 - SpringBoot中yaml配置对象
		
转载请在页首注明作者与出处 一:前言 YAML可以代替传统的xx.properties文件,但是它支持声明map,数组,list,字符串,boolean值,数值,NULL,日期,基本满足开发过程中的所 ...
 - Json CPP 中文支持与入门示例
		
在每一个Json Cpp自带*.cpp文件头加上: #include "stdafx.h" 将Json Cpp对自带的头文件的引用修改为单引号方式,例如json_reader.cp ...
 - cpp 调用python
		
在用cpp调用python时, 出现致命错误: no module named site , 原因解释器在搜索路径下没有找到python库.可以在调用Py_Initialize前,调用 Py_Se ...
 - nginx+fastcgi+c/cpp
		
参考:http://github.tiankonguse.com/blog/2015/01/19/cgi-nginx-three/ 跟着做了一遍,然后根据记忆写的,不清楚有没错漏步骤,希望多多评论多多 ...
 - APM程序分析-ArduCopter.cpp
		
该文件是APM的主文件. #define SCHED_TASK(func, rate_hz, max_time_micros) SCHED_TASK_CLASS(Copter, &copter ...
 - APM程序分析-AC_WPNav.cpp
		
APM程序分析 主程序在ArduCopter.cpp的loop()函数. /// advance_wp_target_along_track - move target location along ...
 - Dev Cpp 输出中文字符问题
		
最近 c++ 上机作业,vc++6.0 挂了没法用,只好用 Dev Cpp 先顶替一下,然而在遇到输出中文字符的时候出现了乱码的情况,但这种情况又非常诡异.于是简单了解了一下写成此博客. [写在前面] ...
 
随机推荐
- Linux 工作目录切换命令
			
1.pwd 显示当前用户所处的目录 2.cd 切换工作路径 cd [目录名称],cd - 返回上次所处的目录 cd ~ 返回当前用户的根目录 cd.. 返回上级目录 3.ls 显示目录中的文件信息,l ...
 - vue-Swiper-awsome
			
<swiper :options="swiperOption"> <swiper-slide><img src="static/images ...
 - PHP批量保存图片
			
关于这个问题网上也有回答,我只是把我在工作中用到的代码分解出来,供需要的朋友使用.以下代码都已经经过测试,所以没有任何问题.有问题请加QQ:1127173874 第一部分 数据库表结构 create ...
 - vue.js响应式原理解析与实现
			
vue.js响应式原理解析与实现 从很久之前就已经接触过了angularjs了,当时就已经了解到,angularjs是通过脏检查来实现数据监测以及页面更新渲染.之后,再接触了vue.js,当时也一度很 ...
 - websocket的子协议stomp协议
			
stomp协议Spring实现 服务器注册EndPoint 用来与客户端建立websocket连接 websocket连接的建立应该与客户端与服务器之间的通道无关 jdk中 javax下的websoc ...
 - 阅读rocketmq技术内幕、实战与原理杂记 - 设计
			
最近正在研究rocketmq,简单记录下设计的不同 互联网系统中Rpc.服务治理.消息中间件基本都是标配,消息中间件能解耦,削峰,高可用并能间接提供达到最终一致性 消息中间件中,消息消费分为最多一次, ...
 - 一个jQuery对象绑定多个事件
			
1.两个事件有两种不同的方法 jQuery("#id").click(func1(){}).mouseover(func2(){}) ; 2.两个事件调用同一种方法 jquery( ...
 - 最大矩阵(简单DP)
			
见题: 很水的一题,数据范围太小,前缀和加爆搜就行. #include<bits/stdc++.h> using namespace std; ; ,m,n,sum[maxn][maxn] ...
 - linux下面重启nfs报错:nfs-server.service:main process exited
			
linux下面重启nfs报错:nfs-server.service:main process exited [root@dhcp-66-83-39 images]# service rpcbind s ...
 - java使用selenium版本不兼容解决汇总
			
selenium之webDriver与浏览器版本问题 http://blog.csdn.net/xqhadoop/article/details/77892796 selenium自动化测试资源整理( ...