c++ - 如何读取 UCS-2 文件?

标签 c++ unicode encoding character-encoding wofstream

我正在编写一个程序来获取 UCS-2 Little Endian 中 *.rc 文件编码的信息。

int _tmain(int argc, _TCHAR* argv[]) {
  wstring csvLine(wstring sLine);
  wifstream fin("en.rc");
  wofstream fout("table.csv");
  wofstream fout_rm("temp.txt");
  wstring sLine;
  fout << "en\n";
  while(getline(fin,sLine)) {
    if (sLine.find(L"IDS") == -1)
      fout_rm << sLine << endl;
    else
      fout << csvLine(sLine);
  }
  fout << flush;
  system("pause");
  return 0;
}

“en.rc”的第一行是#include <windows.h>但是sLine显示如下:

[0]     255 L'ÿ'
[1]     254 L'þ'
[2]     35  L'#'
[3]     0
[4]     105 L'i'
[5]     0
[6]     110 L'n'
[7]     0
[8]     99  L'c'
.       .
.       .
.       .

这个程序可以正确运行 UTF-8。我怎样才能做到 UCS-2?

最佳答案

宽流使用宽流缓冲区来访问文件。宽流缓冲区从文件中读取字节并使用其 codecvt facet 将这些字节转换为宽字符。默认的 codecvt 方面是 std::codecvt<wchar_t, char ,std::mbstate_t>,它在 wchar_tchar 的 native 字符集之间进行转换(即,像 mbstowcs( 那样)。

您没有使用 native char 字符集,因此您需要的是一个 codecvt facet,它将 UCS-2 读取为多字节序列并将其转换为宽字符。

#include <fstream>
#include <string>
#include <codecvt>
#include <iostream>

int main(int argc, char *argv[])
{
    wifstream fin("en.rc", std::ios::binary); // You need to open the file in binary mode

    // Imbue the file stream with a codecvt facet that uses UTF-16 as the external multibyte encoding
    fin.imbue(std::locale(fin.getloc(),
              new std::codecvt_utf16<wchar_t, 0xffff, consume_header>));

    // ^ We set 0xFFFF as the maxcode because that's the largest that will fit in a single wchar_t
    //   We use consume_header to detect and use the UTF-16 'BOM'

    // The following is not really the correct way to write Unicode output, but it's easy
    std::wstring sLine;
    std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> convert;
    while (getline(fin, sLine))
    {
        std::cout << convert.to_bytes(sLine) << '\n';
    }
}

请注意,此处 UTF-16 存在问题。 wchar_t 的目的是让一个 wchar_t 代表一个代码点。但是 Windows 使用 UTF-16 将一些代码点表示为两个 wchar_t s。这意味着标准 API 不能很好地与 Windows 一起工作。

这里的结果是,当文件包含代理项对时,codecvt_utf16 将读取该对,将其转换为大于 16 位的单个代码点值,并且必须将该值截断为 16 位以将其粘贴到 wchar_t 中。这意味着此代码实际上仅限于 UCS-2 。我已将 maxcode 模板参数设置为 0xFFFF 以反射(reflect)这一点。

wchar_t 还有很多其他问题,您可能想完全避免它:What's “wrong” with C++ wchar_t?

关于c++ - 如何读取 UCS-2 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11643500/

相关文章:

java - 是否有任何将 CAD 转换为 SVG 的库?

windows - 两个 TCHAR 的不区分大小写的比较

java - 如何使用 java 和 PDFBox 从 PDF 中获取字符的 Unicode

php - 使用编码为 UTF-8 的 PDFTk 填充的 pdf 中缺少字符

c++ - matlab神经网络工具箱

c++ - 模板类中的 typedef 语句

.net - 使用 System.Text.UnicodeEncoding.Unicode.GetString(byte[]) 反向编码字节数组时间歇性失败

java - 获取请求的 UTF-8 JSF 编码参数

c++ - 自动生成 move 操作的规则是什么?

c# - 为什么这个正则表达式返回真?