boost - how to get properties within subsections of a ini file with boos property tree? -
i trying use boost property trees read ini
files containing properties within sections have "composed" path name.
for example ini
file looks this:
[my.section.subsection1] someprop1=0 [my.section.subsection2] anotherprop=1
i read following code:
namespace pt = boost::property_tree; pt::ptree proptree; pt::read_ini(filepath, proptree); boost::optional<uint32_t> someprop1 = pt.get_optional<uint32_t>("my.section.subsection1.someprop1");
the problem never value of someprop1
...
when iterate on first tree level see the entire section name my.section.subsection1
key. there way make read_ini
function parse section names dots tree hierarchy?
if want property tree reflect hierarchy, requires writing custom parser. per ini parser documentation:
ini simple key-value format single level of sectioning. [...] not property trees can serialized ini files.
because of single level sectioning, my.section.subsection1
must treated key, rather hierarchy path. example, my.section.subsection1.someprop1
path broken down into:
key separator value .----------^---------. ^ .---^---. |my.section.subsection1|.|someprop1|
because "." part of key, boost::property_tree::string_path
type must explicitly instantiated different separator. available path_type
typedef on ptree
. in case, have opted use "/":
ptree::path_type("my.section.subsection1/someprop1", '/')
with example.ini containing:
[my.section.subsection1] someprop1=0 [my.section.subsection2] anotherprop=1
the following program:
#include <iostream> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> int main() { namespace pt = boost::property_tree; pt::ptree proptree; read_ini("example.ini", proptree); boost::optional<uint32_t> someprop1 = proptree.get_optional<uint32_t>( pt::ptree::path_type( "my.section.subsection1/someprop1", '/')); boost::optional<uint32_t> anotherprop = proptree.get_optional<uint32_t>( pt::ptree::path_type( "my.section.subsection2/anotherprop", '/')); std::cout << "someprop1 = " << *someprop1 << "\nanotherprop = " << *anotherprop << std::endl; }
produces following output:
someprop1 = 0 anotherprop = 1
Comments
Post a Comment