Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ YAML: How to edit/write to a node in a .yaml file

Tags:

c++

yaml

yaml-cpp

I am trying to write a function that will write/edit a node in my .yaml file using yaml-cpp. I kind of got it working as my code will edit the local copy. When I print out _baseNode it shows that the node has the value 5.4 in it. However, after exiting the function and checking my .yaml on my computer the value 5.4 is not there.

Here is my attempt (_baseNode is a private member of my class):

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;

}

For my second attempt, I created a YAML::Node& baseNode:

YAML::Node& baseNode = YAML::LoadFile(_parameterFileName);

but then I get this error:

invalid initialization of non-const reference of type 'YAML::Node&' from an rvalue of type 'YAML::Node'

For those who are interested, the .yaml file looks like this:

chip:
  clock_rate:
    0: 1.0
    1: 1.0
    2: 1.0
    3: 3.0
    4: 1.0

I want to change the value mapped by 3 from 3.0 to 5.4.

like image 874
jlcv Avatar asked Feb 12 '23 01:02

jlcv


1 Answers

Like what @filmor said in the comments, LoadFile only loads the data into memory and does not provide an interface to the filesystem.

Thus, edit a .yaml file, you must first edit the root node of the file and dump it back into the file like so:

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
like image 200
jlcv Avatar answered Feb 15 '23 09:02

jlcv