用c ++读取UTF-16文件

时间:2018-06-05 09:37:11

标签: c++ utf-16

我正在尝试读取带有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 version 3.8.0-2ubuntu4(tags / RELEASE_380 / final)
  • clang version 5.0.0-3~16.04.1(tags / RELEASE_500 / final)

2 个答案:

答案 0 :(得分:2)

理想情况下,您应该以UTF8格式保存文件,因为Window具有更好的UTF8支持(除了在控制台窗口中显示Unicode),而POSIX具有有限的UTF16支持。甚至微软的产品都支持UTF8在Windows中保存文件。

作为替代方案,您可以将UTF16文件读入缓冲区并将其转换为UTF8

std::ifstream fin("utf16.txt", std::ios::binary);
fin.seekg(0, ios::end);
size_t size = (size_t)fin.tellg();

//skip BOM
fin.seekg(2, ios::beg);
size -= 2;

std::u16string u16((size / 2) + 1, '\0');
fin.read((char*)&u16[0], size);

std::string utf8 = std::wstring_convert<
    std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(u16);

<小时/> 或者

std::ifstream fin("utf16.txt", std::ios::binary);

//skip BOM
fin.seekg(2);

//read as raw bytes
std::stringstream ss;
ss << fin.rdbuf();
std::string bytes = ss.str();

//make sure len is divisible by 2
int len = bytes.size();
if(len % 2) len--;

std::wstring sw;
for(size_t i = 0; i < len;)
{
    //little-endian
    int lo = bytes[i++] & 0xFF;
    int hi = bytes[i++] & 0xFF;
    sw.push_back(hi << 8 | lo);
}

std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert;
std::string utf8 = convert.to_bytes(sw);

答案 1 :(得分:0)

替换为 - std::wstring::npos(不是std::string::npos) - ,您的代码必须有效:

...
 //std::wcout << wstr << std::endl;

  if (wstr.find(L"Test") == std::wstring::npos) {
    std::cout << "Not Found" << std::endl;
  } else {
    std::cout << "found" << std::endl;
  }