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?
提升1.53
我用它跳过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();
}
-
是的,最简单的选择是检查文件是否以BOM开头并将其删除
-
你可以针对boost(可能应该)提交一个错误
-
只要找到BOM,就可以使用boost::iostums过滤器从输入流中删除BOM:
- 筛选器使用情况
- 滤波器概念
- 输入过滤器概念,带有可适用于删除BOM的示例