作者sbrhsieh (sbr)
看板C_and_CPP
标题Re: [问题] C++读写utf-16
时间Sat Mar 28 14:10:55 2009
※ 引述《tsaiminghan (nahgnimiast)》之铭言:
: 环境 vs2005
: 我知道win32 api可以正常运作,我想问的是
: 一般c++如何处理unicode的档案,
: 我试了使用iwfstream/owfstream,发现
: 这两个读写时,读进来的资料是以1byte大小作单位,
: 也就是说如果是2bytes的utf16,读进来的资料都需要
: 2个单位的阵列元素来储存,造成读进来的资料没办法
: 很简单的作字串的比较(ex 使用wcscmp, strcmp),请
: 问一般C++的作法是?
UTF16 有分 UTF16-LE 与 UTF16-BE。
在 Windows 要处理 UTF16-LE 编码的文字档,可以使用 wifstream/wofstream
来存取。
wifstream 虽然是 elem 与 char traits 皆为 wchar_t 的 basic_ifstream,但
他内部预设使用的 buffer 依然是 char(byte),所以你要自己更换 buffer。
测试一下:
#include "stdafx.h"
#include <fstream>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
wifstream::char_type buf[32000];
wifstream::char_type line[300];
wifstream is("c:\\readme.txt", ios::in | ios::binary);
is.rdbuf()->pubsetbuf(buf, sizeof(buf) / sizeof(buf[0]));
is.getline(line, sizeof(line) / sizeof(line[0]));
cout << "Read chars count: " << wcslen(line) << endl;
for (int i = 0; i < wcslen(line); ++i)
cout << "[" << i << "] "
<< hex << static_cast<unsigned short>(line[i])
<< dec << endl;
return 0;
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 218.173.136.118
※ 编辑: sbrhsieh 来自: 218.173.136.118 (03/28 14:13)
1F:推 chrisdar:buf 32000 那原先的BUF数量是多少 03/28 15:42
2F:→ tsaiminghan:请问一下buf的大小要设多少才够? 03/28 18:57
3F:→ tsaiminghan:是否只要大於一次读取字串大小就行了? 03/28 18:59
4F:→ tsaiminghan:谢谢,换buf的方法真好用,我本来还想要自行把char对 03/28 19:32
5F:→ tsaiminghan:应到wchar_t 03/28 19:33