4

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.

jlcv
  • 1,688
  • 5
  • 21
  • 50
  • What do you expect `LoadFile` to do? It's pretty clear that it loads the data into memory and does not provide a magical interface to the filesystem. You have to explicitly write the changed tree back to the filesystem using the `Emitter` API, check http://stackoverflow.com/questions/3342355/save-a-yaml-emitter-content-to-a-file-with-yaml-cpp. – filmor Jan 27 '15 at 13:45
  • Oh okay, that makes sense. I thought based on the tutorial (https://code.google.com/p/yaml-cpp/wiki/Tutorial#Building_Nodes) I could just build nodes onto the file. I will look into this `Emitter` API then, cheers :) – jlcv Jan 27 '15 at 13:49

1 Answers1

8

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
werk
  • 342
  • 2
  • 12
jlcv
  • 1,688
  • 5
  • 21
  • 50