【发布时间】:2018-06-05 09:37:10
【问题描述】:
我正在尝试使用 BOM 读取具有 UTF-16LE 编码的文件。 我试过这段代码
#include <iostream>
#include <fstream>
#include <locale>
#include <codecvt>
int main() {
std::wifstream fin("/home/asutp/test");
fin.imbue(std::locale(fin.getloc(), new std::codecvt_utf16<wchar_t, 0x10ffff, std::consume_header>));
if (!fin) {
std::cout << "!fin" << std::endl;
return 1;
}
if (fin.eof()) {
std::cout << "fin.eof()" << std::endl;
return 1;
}
std::wstring wstr;
getline(fin, wstr);
std::wcout << wstr << std::endl;
if (wstr.find(L"Test") != std::string::npos) {
std::cout << "Found" << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
文件可以包含拉丁文和西里尔文。我用字符串“Test тест”创建了文件。这段代码返回了我
/home/asutp/CLionProjects/untitled/cmake-build-debug/untitled
Not found
Process finished with exit code 0
我使用的是 Linux Mint 18.3 x64、Clion 2018.1
试过
- gcc 版本 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.9)
- clang 版本 3.8.0-2ubuntu4 (tags/RELEASE_380/final)
- clang 版本 5.0.0-3~16.04.1 (tags/RELEASE_500/final)
【问题讨论】:
-
我的测试文件rgho.st/7xH6WMcGZ
-
打印出
wstr中的内容? -
@PaulSanders 有 std::wcout
-
抱歉,错过了。我不是
std::codecvt方面的专家,但您可以考虑切换到std::basic_string<char16_t>和代码u"Test"而不是L"Test",从而完全不需要它。 -
这段代码对我来说很好用。你确定你的文件有BOM吗?