Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect parse/read failure of Boost.PropertyTree?

Tags:

c++

boost

The documentation doesn't really say.

I get that I can hand it an ifstream, so I could check to make sure it's open, so that case is mostly dealt with.

But when doing boost::property_tree::ini_parser::read_ini(ifstream_object,property_tree_object);

How do I detect if the file was in a bad format? Is there any way for me to get diagnostic information, such as where the parse failed?

like image 339
Fred Avatar asked Dec 03 '12 08:12

Fred


1 Answers

Just catch exceptions. Base PropertyTree exception class is boost::property_tree::ptree_error which derives from std::runtime_error, and it has two descendants: ptree_bad_data and ptree_bad_path.

Example:

#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <iostream>
#include <sstream>

int main()
{
    using namespace std;
    using namespace boost;
    using namespace property_tree;

    stringstream ss;
    ss << "good = value" << endl;
    ss << "bad something" << endl;
    try
    {
        ptree root;
        read_ini(ss, root);
    }
    catch(const ptree_error &e)
    {
        cout << e.what() << endl;
    }
}

Output is:

<unspecified file>(2): '=' character not found in line
like image 175
Evgeny Panasyuk Avatar answered Sep 24 '22 02:09

Evgeny Panasyuk