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

时间:2013-07-16 13:11:14

标签: c++ boost unicode utf-8

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

#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

  

富= STR

输出

  

从配置文件获取选项时发生错误:没有此类节点   (富)

我能用它做什么?手动从文件床上删除BOM读取它?

提升1.53

2 个答案:

答案 0 :(得分:1)

我用它来跳过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();
    }

答案 1 :(得分:0)

  1. 是的,最简单的选择就是检查文件是否以BOM开头并将其删除。

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

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