Boost学习之读写ini文件

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

在程序开发中,配置文件扮演着很重要的角色,实现程序的灵活配置,方便不同环境下部署和使用,对于一些随着外界环境变化的参数,直接写入配置文件。本文将介绍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源码可以看出,初始化流程如下:

  1. 打开文件流;
  2. 逐行读取文件,解析为property tree
  3. 将解析后的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
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值