boost读写ini配置文件

[setting]
key1 = 1  
key2 = hello
上面是文件的内容(内容中不能有注释), 运行如下代码:

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

int main()
{
    boost::property_tree::ptree lvptProperties;
    boost::property_tree::ini_parser::read_ini("hao.txt", lvptProperties);
    boost::property_tree::basic_ptree<std::string, std::string> lvbtItems = lvptProperties.get_child("setting");

    for (auto lvitem=lvbtItems.begin();lvitem!=lvbtItems.end();lvitem++)
    {
        std::cout << (*lvitem).first.data() << "=" << (*lvitem).second.data() << std::endl;
    }
    int lvnInt = 0;
    try
    {
        lvnInt = lvbtItems.get<int>("key1");
        std::cout << lvnInt << std::endl;
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }

    lvptProperties.put<std::string>("setting.key2", "new value");
    lvptProperties.put<std::string>("setting.key3", "new value");
    lvptProperties.put<int>("setting.key1", ++lvnInt);

    boost::property_tree::ini_parser::write_ini("hao.txt", lvptProperties);

    return 0;
}

运行结果:

key1=1
key2=hello
1

然后再重新打开hao.txt看内容:

--------------------- 
作者:OK_boom 
来源:CSDN 
原文:https://blog.csdn.net/rocklee/article/details/76021259 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/f110300641/article/details/84337891