C++ Boost PropertyTree 解析INI文件


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

#include 
#include 
#include   
#include 

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("address");
    int port = tag.get("port");
    std::cout << "地址: " << address << " 端口: " << port << std::endl;

    std::system("pause");
    return 0;
}

相关