3

boost::property_tree::ptree 是否无法处理使用 UTF-8 和 BOM 的文件?

#include <boost/filesystem.hpp>
#include <boost/property_tree/ini_parser.hpp>

#include <cstdlib>
#include <iostream>

int main()
{
    try
    {
        boost::filesystem::path path("helper.ini");
        boost::property_tree::ptree pt;
        boost::property_tree::read_ini(path.string(), pt);
        const std::string foo = pt.get<std::string>("foo");
        std::cout << foo << '\n';
    }
    catch (const boost::property_tree::ini_parser_error& e)
    {
        std::cerr << "An error occurred while reading config file: " << e.what() << '\n';
        return EXIT_FAILURE;
    }
    catch (const boost::property_tree::ptree_bad_data& e)
    {
        std::cerr << "An error occurred while getting options from config file: " << e.what() << '\n';
        return EXIT_FAILURE;
    }
    catch (const boost::property_tree::ptree_bad_path& e)
    {
        std::cerr << "An error occurred while getting options from config file: " << e.what() << '\n';
        return EXIT_FAILURE;
    }
    catch (...)
    {
        std::cerr << "Unknown error \n";
        return EXIT_FAILURE;
    }
}

助手.ini

富=str

输出

从配置文件获取选项时出错:没有这样的节点(foo)

我能用它做什么?手动从文件中删除BOM 阅读它?

提升 1.53

4

2 回答 2

2

I'm using this to skip BOM characters:

    boost::property_tree::ptree pt;
    std::ifstream file("file.ini", std::ios::in);
    if (file.is_open())
    {
        //skip BOM
        unsigned char buffer[8];
        buffer[0] = 255;
        while (file.good() && buffer[0] > 127)
            file.read((char *)buffer, 1);

        std::fpos_t pos = file.tellg();
        if (pos > 0)
            file.seekg(pos - 1);

        //parse rest stream
        boost::property_tree::ini_parser::read_ini(file, pt);

        file.close();
    }
于 2015-06-17T08:49:09.923 回答
0
  1. 是的,最简单的选择是检查文件是否以 BOM 开头并将其删除。

  2. 您可以针对 boost 提交错误(可能应该)

  3. 您可以使用 boost::iosteams 过滤器在找到时从输入流中删除 BOM:

于 2013-07-16T15:05:09.847 回答