【问题标题】:boost::property_tree::ptree and UTF-8 with BOMboost::property_tree::ptree 和带有 BOM 的 UTF-8
【发布时间】:2013-07-14 16:31:14
【问题描述】:

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

输出

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

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

提升 1.53

【问题讨论】:

    标签: c++ boost unicode utf-8


    【解决方案1】:
    1. 是的,最简单的选择是检查文件是否以 BOM 开头并将其删除。

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

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

    【讨论】:

      【解决方案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();
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-30
        • 2015-03-19
        • 2011-12-30
        • 2012-02-12
        • 2014-03-10
        • 1970-01-01
        • 2013-05-20
        • 1970-01-01
        相关资源
        最近更新 更多