5

我正在编写一个程序来获取 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 做到这一点?

4

2 回答 2

10

宽流使用宽流缓冲区来访问文件。Wide 流缓冲区从文件中读取字节,并使用其 codecvt facet 将这些字节转换为宽字符。默认的 codecvt facet 是std::codecvt<wchar_t, char ,std::mbstate_t>在本地字符集 forwchar_tchar(即,like mbstowcs()之间转换)。

您没有使用本机 char 字符集,因此您想要的是一个 codecvt 方面,它读取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_ts。这意味着标准 API 在 Windows 上不能很好地工作。

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

有许多其他问题wchar_t,您可能只想完全避免它:C++ wchar_t 有什么“错误”?

于 2012-07-25T17:34:35.623 回答
0
#include <filesystem>
namespace fs = std::filesystem;

    FILE* f = _wfopen(L"myfile.txt", L"rb");
    auto file_size = fs::file_size(filename);
std::wstring buf;       
buf.resize((size_t)file_size / sizeof(decltype(buf)::value_type));// buf in my code is a template object, so I use decltype(buf) to decide its type.
    fread(&buf[0], 1, 2, f); // escape UCS2 BOM
    fread(&buf[0], 1, file_size, f);
于 2020-11-24T08:56:54.037 回答