我正在编写一个程序来获取 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_t
和 char
的 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/