boost::property_tree::ptree和UTF-8带BOM

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;
    }
}

helper.ini

foo=str

输出

从配置文件获取选项时出现错误:找不到节点(foo)

我该怎么做?在读取文件之前手动删除BOM吗?

boost 1.53

2个回答

2
我正在使用这个来跳过BOM字符:
    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();
    }

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接