c++ - boost 属性树 毫无意义的错误路径

标签 c++ exception boost boost-propertytree

我在使用这个库时遇到问题...我的代码工作正常,解析器/创建器也工作,但出现错误,我不知道为什么:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/thread.hpp>
#include <string>
#include <exception>
#include <set>
#include <iostream>
#include "journal.h"

unsigned short port                 = 2013;
unsigned short maxConnec            = 250;

unsigned short fPort()                 {return port;}
unsigned short fMaxConnec()            {return maxConnec;}

bool load(const std::string &file)
{
    using boost::property_tree::ptree;
    ptree objectXML;
    std::cout << "bbb";
    read_xml(file, objectXML);
    std::cout << "aaa";
    if (file.length() == 0) // By the way, no way to do that better ? "if file doesn't exist..."
    {
        return 0;
    }
    else
    {
        port                    = objectXML.get<unsigned short>("configuration.server.port");
        maxConnec            = objectXML.get<unsigned short>("configuration.server.maxConnections");
        return 1;
    }
}

bool save(const std::string &file)
{
    try
    {
        using boost::property_tree::ptree;
        ptree objectXML;
        objetXML.put("configuration.server.port", port);
        objetXML.put("configuration.server.maxConnections", maxConnec);
        write_xml(file, objectXML, std::locale(), boost::property_tree::xml_writer_make_settings<ptree::key_type>(' ', 4));
        return 1;
    }
    catch (std::exception e)
    {
        return 0;
    }
}

void generate()
{

    std::string file = "configuration.xml";
    try{
        if (!load(fichier))
        {
            save(file);
        }
    }
    catch (std::exception &e)
    {
        load(file);
    }
}

得到一个错误的路径,我完全不知道为什么,因为当我尝试读取数据时,我可以并且它在 configuration.xml 中获取数据,即使我更改它......

最佳答案

ptree_bad_path get 的抛出版本引发异常并表示 "configuration.server.port""configuration.server.maxConnections"XML 元素 的路径不存在。

错误与 configuration.xml 文件路径无关。

因此您应该检查元素名称,或者对于可选元素,使用 default-value / optional-value version of get .

关于c++ - boost 属性树 毫无意义的错误路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27774011/

相关文章:

c++ - 使用 Oculus Rift 时相机抖动

c++ - 在已在源中重载的 header 中使用模板中的方法

java - XStream、循环引用异常

c++ - 你如何处理 Boost 中的大依赖?

c++ - Boost boyer_moore 搜索语料库类型的示例类?

c++ - 如何在 C++ 中扩展 listControl 类并添加新功能?

Kotlin:尝试,捕捉,并且只有在最后出现错误时

java - 如果两个进程同时更新一个 Collection 那么会引发哪个异常?

c++ - 如何从 boost::filesystem::filesystem_error 获取错误代码的含义

c++ - 如何在 C 函数中使用 std::vector