简体   繁体   中英

How often does boost::property_tree parse a property file?

I need to read properties from a file to affect program behavior. Looks like boost::property_tree will do quite nicely. But, I'm wondering if when fetching different kinds of values that the library may reads the file multiple times?

For performance reason I'd like it to only be once. Most of the properties will be simple values like numbers, and strings. But occasionally there will be lists of numbers and lists strings.

I figure the it parses the file only once, but you never know and hence the question.

thanks.

You control it, and it reads only once:

//
// All that is required to read an xml file into the tree
//

std::ifstream in("region.xml");
boost::property_tree::ptree result_tree;
boost::property_tree::read_xml(in,result_tree);

Include the correct header and read ini, json or xml files into the tree using the corresponding read_XXX method.

You then use a "path" to access elements from the tree, or you can iterate over subtrees

BOOST_FOREACH(boost::property_tree::ptree::value_type &v,result_tree.get_child("gpx.rte"))
{
      if( v.first == "rtept" ) //current node/element name
      {
           boost::property_tree::ptree subtree = v.second ;
           //A path to the element is required to access the value
          const int lat = sub_tree.get<double>( "<xmlattr>.lat")*10000.0;
          const int lon = sub_tree.get<double>( "<xmlattr>.lon")*10000.0;
      }
}

or direct access via a path:

  // Here is simplistic access of the data, again rewritten for flexibility and 
  // exception safety in real code (nodes shortened too)
  const int distVal = 
       result_tree.get<int>
        ( "Envelope.Body.MatrixResponse.Matrix.Route.<xmlattr>.distance")/1000;

Every time you want to read you can check if the file has changed. If yes, then you can read it.

char filename[] = "~/test.txt";
char timeStr[100] = "";
struct stat buf;
time_t ltime;
char datebuf[9];
char timebuf[9];
if (!stat(filename, &buf)) {
    strftime(timeStr, 100, "%d-%m-%Y %H:%M:%S", localtime(&buf.st_mtime));
    printf("\nLast modified date and time = %s\n", timeStr);
}
else {
    printf("error getting atime\n");
}

_strtime(timebuf);
_strdate(datebuf);
printf("\nThe Current time is %s\n",timebuf);
printf("\nThe Current Date is %s\n",datebuf);
time(&ltime);

if (difftime(ltime ,buf.st_mtime) > 0) {
   // Read it.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM