php 网站迁移,个性化定制网站有哪些,长春网络推荐,河北工程大学网站开发成本在日常的代码中#xff0c;有一些值是配置文件中定义的#xff0c;这些值可以根据用户的要求进行调整和改变。这往往会写在yaml格式的文件中。这样开放程序给用户时#xff0c;就可以不必开放对应的源码#xff0c;只开放yaml格式的配置文件即可。
将配置文件中的值读入程…在日常的代码中有一些值是配置文件中定义的这些值可以根据用户的要求进行调整和改变。这往往会写在yaml格式的文件中。这样开放程序给用户时就可以不必开放对应的源码只开放yaml格式的配置文件即可。
将配置文件中的值读入程序也非常的简单。
我们先写一个简单的配置文件然后将其中的值读入到程序中。配置文件如下
general_test:test_name: yaml_testis_debug: truefile_path: ./int_value:test_time: 2
需要注意的是这里面变量的值在读入程序之初是没有类型的。但是读入之后其实是有对应需要的类型的比如is_debug读入后需要时bool类型test_time读入之后需要是int类型。
下面写个C程序做读入上面配置文件的简单验证。
首先需要引用头文件
#include yaml-cpp/yaml.h
有几个需要注意的地方
1. yaml文件是分级写入的在C程序中也需要分级读取或者看成总节点和子节点的关系。如程序中config表示总文件节点要读取第二级的test_name就需要进行两层的穿透。另外上面提到的类型问题在这里用.as来体现将对应的配置文件中的值读入成程序中期望得到的值的类型这里test_name希望读入为string。
config[general_test][test_name].asstd::string()
2. 层级过多的时候防止一行输入过多。可以定义子节点名称然后从子节点开始寻值。 YAML::Node subnode config[general_test];const bool is_debug subnode[is_debug].asbool();const int test_time subnode[int_value][test_time].asint();
完整的代码如下
#include iostream
#include yaml-cpp/yaml.hint main()
{std::string file yaml_test.yaml;// 使用loadfile加载要读取的配置文件路径YAML::Node config YAML::LoadFile(file);// 通过如下格式获取配置文件中对应项的值const std::string name config[general_test][test_name].asstd::string();// 配置文件分级较多时可以设置子节点 YAML::Node subnode config[general_test];const bool is_debug subnode[is_debug].asbool();const int test_time subnode[int_value][test_time].asint();std::cout test name is: name std::endl;std::cout is_debug is: is_debug std::endl;std::cout test time is: test_time std::endl;return 0;
}最后在编译的时候注意需要带上yaml的库
g yaml_test.cpp -lyaml-cpp
运行结果如下
test name is: yaml_test
is_debug is: 1
test time is: 2