我正在尝试编写一个函数,用于在我的.yaml文件中编写/编辑节点yaml-cpp.我有点工作,因为我的代码将编辑本地副本.当我打印出来时,_baseNode它显示节点的值为5.4.但是,在退出该功能并.yaml在我的计算机上检查后,值5.4不存在.
这是我的尝试(_baseNode是我班级的私人成员):
void ParametersServerPC::testFunc2() {
boost::filesystem::path path(boost::filesystem::initial_path() / _parameterFileName);
_baseNode = YAML::LoadFile(_parameterFileName);
_baseNode["chip"]["clock_rate"]["3"] = 5.4;
std::cout << _baseNode << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
对于我的第二次尝试,我创建了一个YAML::Node& baseNode:
YAML::Node& baseNode = YAML::LoadFile(_parameterFileName);
Run Code Online (Sandbox Code Playgroud)
但后来我收到这个错误:
invalid initialization of non-const reference of type 'YAML::Node&' from an rvalue of type 'YAML::Node'
Run Code Online (Sandbox Code Playgroud)
对于那些感兴趣的人,.yaml文件看起来像这样:
chip:
clock_rate:
0: 1.0
1: 1.0
2: 1.0
3: 3.0
4: 1.0
Run Code Online (Sandbox Code Playgroud)
我想将映射的值3从3.0 更改为5.4.
就像@filmor在评论中所说的那样,LoadFile只将数据加载到内存中,而不提供文件系统的接口.
因此,编辑.yaml文件时,必须先编辑文件的根节点,然后将其转储回文件中,如下所示:
YAML::Node node, _baseNode = YAML::LoadFile("file.yaml"); // gets the root node
_baseNode["change"]["this"]["node"] = "newvalue"; // edit one of the nodes
std::ofstream fout("fileUpdate.yaml");
fout << _baseNode; // dump it back into the file
Run Code Online (Sandbox Code Playgroud)