Re: [問題] C++讀寫utf-16
※ 引述《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)
推
03/28 15:42, , 1F
03/28 15:42, 1F
→
03/28 18:57, , 2F
03/28 18:57, 2F
→
03/28 18:59, , 3F
03/28 18:59, 3F
→
03/28 19:32, , 4F
03/28 19:32, 4F
→
03/28 19:33, , 5F
03/28 19:33, 5F
討論串 (同標題文章)