YAML文件实例详解
//突然接触到配置文件,虽然看似挺简单的配置文件数据调用,但实际还是会犯错。
1 yaml文件作用相比之前已经有查阅过,我就不做重复工作。简单概述以下要点
/*yaml文件的语法
在yaml里面,结构通过缩进表示,连续的项目(如 数组元素,结合元素)通过减号 - 来表示,map结构里面的键值对(key/value)用冒号来分割
yaml也有用描述好几行相同结构数据的缩写语法,数组用[]包括起来,hash用{}来包括
1,在yaml中结构通过缩进表示,不支持制表符tab请用空格缩进
2,如果参数是以空格开始或结束的字符串,应使用单引号把他包进来
3,每个冒号后面一定有一个空格(以冒号结尾不需要空格,表示文件路径的模板可以不需要空格),这里指的是键值
4,想要表示列表项,使用一个短杠加上一个空格,多个项使用同样的缩进级别作为以恶列表一部分
5,yaml中 空值可以使用null或者~
*/
2直接进入实例教学
有这个一个yaml文件 profile_conf.yaml
use_method: 1
use_method2: 0
调用过程
#include<yaml_cpp.yaml.h>
#include<string>
#include<iostream>
using namespace std;
//封装一个类
class ReadYaml
{
public:
ReadYaml(){};
public:
YAML::Node yaml_param = YAML::LoadFile(param_file);
{
YAML::Node yaml_param = YAML::LoadFile(param_file);
return yaml_param;
}
}
//模板类的多种调用方法
template<typename T>
int parse_yaml(const YAML:: Node yaml_node, const string& key, T& value, const T& default_value)
{
if(!yaml_node[key])
{
value = dafault_value;
return RET_ERROR;
}
else
{
valude = yaml_node[key].as<T>();
return RET_OK;
}
}
/*按道理三种方式的模板需要写完,我们只看一个,一个看懂了就都懂了。
template<typename T>
int parse_yaml(const YAML:: Node yaml_node, const string& key1, const string& key2, T& value, const T& default_value)
{
if (!yaml_node[key1][key2])
{
value = default_value;
return RET_ERROR;
}else
{
value = yaml_node[key1][key2].as<T>();
return RET_OK;
}
}
template<typename T>
int parse_yaml(const YAML:: Node yaml_node, const string& key1, const string& key2, const string& key3, T& value, const T& default_value);
*/
int main()
{
int _use_method;
int _use_method2;
const string conf_path = "xxxxxxx绝对路径下的profile_conf.yaml"
load_conf(conf_path);
cout << "_use_method" << _use_method << endl;
cout << "_use_method2" << _use_method2 << endl;
return 0;
}
void load_conf(const string &file_path)
{
ReadYaml readyaml;
YAML::Node parma_node = readyaml.load_conf(file_path);
int ret = 0;
ret = readyaml.parse_yaml(parma_node,"use_method",_use_method,0);
if(ret == RET_ERROR)
{
cout << "use_method读取失败";
}
else
{
cout << "use_method读取成功";
}
ret = readyaml.parse_yaml(parma_node,"use_method2",_use_method2,0);
if(ret == RET_ERROR)
{
cout << "use_method2读取失败";
}
else
{
cout << "use_method2读取成功";
}
return true;
}
仔细看主函数就发先其实,很简单的读取方法。而且还包含读取失败的错误提示。
主要是第一次接触都Yaml文件,包括他的函数调用方法第一次见,还有就是头文件的包含。这些让常见的文件调用有很大的不同。这也配置文件Yaml的魅力所在。