1. 程式人生 > >boost讀寫ini配置檔案

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 
版權宣告:本文為博主原創文章,轉載請附上博文連結!