在程序开发中,配置文件扮演着很重要的角色,实现程序的灵活配置,方便不同环境下部署和使用,对于一些随着外界环境变化的参数,直接写入配置文件。本文将介绍boost总ini配置文件的读写。
初始化ini解析器
在程序开发中,文件读写是很重要的一个环节,同样,boost也提供了强大的文件读写功能,对于C++中经常使用的ini文件,boost直接提供了解析接口,使用者可以很方便的调用。
在boost中,解析ini文件的接口定义在如下文件中。
#include <boost/property_tree/ini_parser.hpp>
boost操作ini文件,是按照树形结构解析读取的,对应的树形结构解析接口位于如下头文件中。
#include <boost/property_tree/ptree.hpp>
初始化init文件的接口为 :read_ini,从boost源码可以看出,初始化流程如下:
- 打开文件流;
- 逐行读取文件,解析为property tree;
- 将解析后的property tree返回给使用者;
后续的读、写、修改都需要基于当前的property tree,该接口的实现源码如下:
/**
* Read INI from a the given file and translate it to a property tree.
* @note Clears existing contents of property tree. In case of error the
* property tree unmodified.
* @throw ini_parser_error In case of error deserializing the property tree.
* @param filename Name of file from which to read in the property tree.
* @param[out] pt The property tree to populate.
* @param loc The locale to use when reading in the file contents.
*/
template<class Ptree>
void read_ini(const std::string &filename,
Ptree &pt,
const std::locale &loc = std::locale())
{
std::basic_ifstream<typename Ptree::key_type::value_type>
stream(filename.c_str()); //open file
if (!stream)
BOOST_PROPERTY_TREE_THROW(ini_parser_error(
"cannot open file", filename, 0));
stream.imbue(loc);
try {
read_ini(stream, pt); //start parse ini file
}
catch (ini_parser_error &e) {
BOOST_PROPERTY_TREE_THROW(ini_parser_error(
e.message(), filename, e.line()));
}
}
/**
* Read INI from a the given stream and translate it to a property tree.
* @note Clears existing contents of property tree. In case of error
* the property tree is not modified.
* @throw ini_parser_error If a format violation is found.
* @param stream Stream from which to read in the property tree.
* @param[out] pt The property tree to populate.
*/
template<class Ptree>
void read_ini(std::basic_istream<
typename Ptree::key_type::value_type> &stream,
Ptree &pt)
{
typedef typename Ptree::key_type::value_type Ch

本文介绍如何使用Boost库进行INI配置文件的读写操作,包括初始化解析器、读取、写入及修改INI文件的方法,适用于不同环境下的程序配置。
最低0.47元/天 解锁文章
1878





