8

I just started playing around with yaml-cpp, I managed to build it properly and run some of the examples from the yaml-cpp wiki but I can't find a way to save my emitter to a file.

Is this not possible? I mean the PyYAML library has a 'dump' function for this. Is there no such functionality in yaml-cpp? Is there some workaround to converting a yaml emitter to a stl stream and then dumping this to a yaml file?

Please let me know

Thanks, Adam

somada141
  • 81
  • 1
  • 2

1 Answers1

9

The function Emitter::c_str() returns a NULL-terminated C-style string (which you do not have to release), which you can then write to a file. For example:

YAML::Emitter emitter;
emitter << "Hello world!";

std::ofstream fout("file.yaml");
fout << emitter.c_str();

There is also Emitter::size(), which returns the number of bytes in that string, in case you want to do something more advanced and don't want to walk the string to find its length.

If you want to just dump a Node to a stream, there's a shortcut:

YAML::Node node = ...;
std::ofstream fout("file.yaml");
fout << node;
Jesse Beder
  • 33,081
  • 21
  • 109
  • 146
  • Just curious, how did you figure out this dumping method? Where do you learn these things. The documentation for `yaml-cpp` is pretty short. – jlcv Jan 27 '15 at 14:39
  • 7
    @JustinLiang I wrote it :) - but you're right, the documentation is a bit short. It's on my TODO list, but, you know... – Jesse Beder Jan 28 '15 at 01:19
  • @JesseBeder Is there a way to save it in same order as `node`? – jlcv Mar 02 '15 at 15:47
  • @JustinLiang - nope, not yet - see https://code.google.com/p/yaml-cpp/issues/detail?id=169 – Jesse Beder Mar 03 '15 at 04:48
  • mmm, so even a large yaml file has to be stored in memory before dumping it to a file? Is there a way to build the yaml into the file directly? – alfC Aug 18 '19 at 10:01