Search code examples
c++boostifstreamofstreamboost-propertytree

Writing and Reading boost Property Tree From/To File?


I want to write a boost::property_tree::ptree binary to a file, and read it out again into a ptree.

Since i´m not very comfort with the ptree and binary writing/reading them.. I thought you guys can lead me into the right direction.

Writing strings, int/float/double isn´t that great problem, but how to store a whole ptree (with unknown keys and values, so it is generic) to a file and read it back in cpp using if-/ofstream?

The Filer Extention will be "*.tgasset" and the File will contain more than the ptree as data.

To make things easier to me.. these are my dummy functions to write/read the data:

void TGS_File::PTreeToFile(std::ofstream &_file, boost::property_tree::ptree _data) {

}

boost::property_tree::ptree TGS_File::PTreeFromFile(std::ifstream &_file) {
    boost::property_tree::ptree _data;

    return _data;
}

(done that with strings, ints, floats and doubles the same way)


Solution

  • You will have to select a format: INI, Json, XML or INFO. Each has their own set of limitations: https://www.boost.org/doc/libs/1_77_0/doc/html/property_tree/parsers.html

    E.g. if you choose JSON:

    #include <boost/property_tree/json_parser.hpp>
    
    void TGS_File::PTreeToFile(std::ofstream &_file, boost::property_tree::ptree _data) {
         write_json(_file, _data);
    }
    
    boost::property_tree::ptree TGS_File::PTreeFromFile(std::ifstream &_file) {
        boost::property_tree::ptree _data;
        read_json(_file, _data);
        return _data;
    }
    

    The procedure is 99% the same for other formats. Roughly speaking (from memory) I suppose the INFO format loses the least amount of information over a roundtrip.