Function sample_parse_file

Synopsis

#include <samples/quickstart.cpp>

void sample_parse_file()

Description

ready-to-go example of parsing a file from disk

demonstrate how to load a YAML file from disk to parse with ryml.

ryml offers no overload to directly parse files from disk; it only parses source buffers (which may be mutable or immutable). It is up to the caller to load the file contents into a buffer before parsing with ryml.

But that does not mean that loading a file is unimportant. There are many ways to achieve this in C++, but for convenience and to enable you to quickly get up to speed, here is an example implementation loading a file from disk and then parsing the resulting buffer with ryml.

Mentioned in

Source

Lines 1226-1258 in samples/quickstart.cpp. Line 50 in samples/quickstart.cpp.

void sample_parse_file()
{
    const char filename[] = "ryml_example.yml";

    // because this is a minimal sample, it assumes nothing on the
    // environment/OS (other than that it can read/write files). So we
    // create the file on the fly:
    file_put_contents(filename, ryml::csubstr("foo: 1\nbar:\n  - 2\n  - 3\n"));

    // now we can load it into a std::string (for example):
    {
        std::string contents = file_get_contents<std::string>(filename);
        ryml::Tree tree = ryml::parse(ryml::to_csubstr(contents)); // immutable (csubstr) overload
        CHECK(tree["foo"].val() == "1");
        CHECK(tree["bar"][0].val() == "2");
        CHECK(tree["bar"][1].val() == "3");
    }

    // or we can use a vector<char> instead:
    {
        std::vector<char> contents = file_get_contents<std::vector<char>>(filename);
        ryml::Tree tree = ryml::parse(ryml::to_substr(contents)); // mutable (csubstr) overload
        CHECK(tree["foo"].val() == "1");
        CHECK(tree["bar"][0].val() == "2");
        CHECK(tree["bar"][1].val() == "3");
    }

    // generally, any contiguous char container can be used with ryml,
    // provided that the ryml::csubstr view can be created out of it.
    // ryml provides the overloads above for these two containers,
    // but if you have a different container it should be very easy
    // (only requires pointer and length).
}





Add Discussion as Guest

Log in