简体   繁体   English

使用BOM提高boost :: property_tree :: ptree和UTF-8

[英]boost::property_tree::ptree and UTF-8 with BOM

Is boost::property_tree::ptree can't handle files which use UTF-8 with BOM? 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 helper.ini

foo=str 富= STR

Output 产量

An error occurred while getting options from config file: No such node (foo) 从配置文件获取选项时发生错误:无此类节点(foo)

What can i do with it? 我该怎么办? Manually delete BOM from file bedore reading it? 手动从文件读取之前删除BOM?

boost 1.53 提升1.53

I'm using this to skip BOM characters: 我正在使用它跳过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. Yes, easiest option would be to just check if the file starts with BOM and remove it. 是的,最简单的选择就是只检查文件是否以BOM表开头并删除它。

  2. You can file a bug against boost (probably should) 您可以提交针对Boost的错误(可能应该这样做)

  3. You could use boost::iosteams filters to remove BOM from the input stream whenever its found: 只要找到输入流,就可以使用boost :: iosteams过滤器从输入流中删除BOM:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM