C++ Boost PropertyTree 解析INI文件

Boost PropertyTree 库不仅可以解析JSON,XML格式,还可以直接解析INI格式文件,并实现对文件的读写操作。

#include <iostream>
#include <string>
#include <boost/property_tree/ptree.hpp>  
#include <boost/property_tree/ini_parser.hpp>

using namespace std;
using namespace boost;

// 写入文件
void init_ini(const std::string &filename)
{
    using boost::property_tree::ptree;
    ptree pt;

    // 增加新的键值对
    pt.add("config.address", "192.168.1.1");
    pt.add("config.port", 22);
    // 修改原有键值对
    pt.put("config.port", 3389);
    write_ini(filename, pt);
}

int main(int argc, char *argv[])
{
    std::string f("c://config.ini");
    init_ini(f);

    // 读取ini文件
    boost::property_tree::ptree ptr, tag;
    boost::property_tree::ini_parser::read_ini("c://config.ini", ptr);

    tag = ptr.get_child("config");
    std::string address = tag.get<std::string>("address");
    int port = tag.get<int>("port");
    std::cout << "地址: " << address << " 端口: " << port << std::endl;

    std::system("pause");
    return 0;
}
文章出处:https://www.cnblogs.com/LyShark/p/15765692.html
版权声明:本博客文章与代码均为学习时整理的笔记,博客中除去明确标注有参考文献的文章,其他文章 [均为原创] 作品,转载请 [添加出处] ,您添加出处是我创作的动力!

如果您恶意转载本人文章并被本人发现,则您的整站文章,将会变为我的原创作品,请相互尊重 !
原文地址:https://www.cnblogs.com/LyShark/p/15765692.html