我需要从文件中读取属性以影响程序行为。看起来像boost :: property_tree会做得很好。但是,我想知道在获取不同类型的值时,库是否可以多次读取文件?
出于表现原因,我希望它只有一次。大多数属性都是简单的值,如数字和字符串。但偶尔会有数字列表和列表字符串。
我认为它只解析文件一次,但你永远不知道,因此问题。
感谢。
答案 0 :(得分:3)
你控制它,它只读一次:
//
// 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);
包含正确的标头,并使用相应的read_XXX方法将ini,json或xml文件读入树中。
然后使用“路径”访问树中的元素,或者可以迭代子树
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;
}
}
或通过路径直接访问:
// 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;
答案 1 :(得分:1)
每次您想要阅读时,您都可以检查文件是否已更改。如果是,那么你可以阅读它。
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(<ime);
if (difftime(ltime ,buf.st_mtime) > 0) {
// Read it.
}