-
2004-04-11
Unicode编码文件的读取 - [C++Builder技术文档]
版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
Unicode就是宽字符编码,它与ANSI编码最大的不同就是一个ANSI编码的位宽是8位,而Unicode的位宽是16位,比如:一个Unicode编码的字符 ’A’ 其16进制编码为0x0041,而同样的字符用ANSI编码就会表示为0x41; 转入正题,不去管Unicode的编码方式,只要能把它识别出来就可以了。Windows SDK中提供了一个API函数,可以把ASCII编码转换为Unicode编码,那就是WideCharToMultiByte()函数,所以编码转换工作就全部交给这个函数了 看一下WideCharToMultiByte()的原型声明: int WideCharToMultiByte( UINT CodePage, // code page DWORD dwFlags, // performance and mapping flags LPCWSTR lpWideCharStr, // address of wide-character string int cchWideChar, // number of characters in string LPSTR lpMultiByteStr, // address of buffer for new string int cchMultiByte, // size of buffer LPCSTR lpDefaultChar, // address of default for unmappable characters LPBOOL lpUsedDefaultChar // address of flag set when default char. used ); 第一个参数使用CP_ACP,第二个参数设为0,第三个参数就是要转换的Unicode字符串的指针,第四个参数,Unicode字符串长度,第五个参数转换到ANSI字符串的指针,第六个参数ANSI字符串的长度 这样就可以把Unicode转换为ANSI编码了,但是还有一个问题,就是如何判断要读入的文件是Unicode编码的还是ANSI编码的?查了一下资料,发现所有Unicode编码的文本文件,其文件头2个字节一定是"0xff","0xfe",这样就好办了,只要先读出这两个字节,然后就可以判断是不是Unicode编码的了。 if( psFirst[0] == ’\xff’ && psFirst[1] == ’\xfe’ )用这条语句就可以判断了。 下面给出C++的一段文件读取代码,返回的就是AnsiString的字符串,这样就可以读取Unicode编码和非Unicode编码的文件了 AnsiString TForm1::ReadUnicodeFromFile(const AnsiString &FileName) { char psFirst[2]; AnsiString str; int iFileHandle = FileOpen( FileName, fmOpenRead ); int iFileLength = FileSeek( iFileHandle, 0, 2 ); FileSeek(iFileHandle, 0, 0); FileRead(iFileHandle, psFirst, 2); //读出文件的头2个字节,用来判断是否为Unicode编码 if( psFirst[0] == ’\xff’ && psFirst[1] == ’\xfe’ ) { wchar_t *wstr=new wchar_t[iFileLength+1]; FileRead(iFileHandle, wstr, iFileLength); FileClose(iFileHandle); int nLen = wcslen(wstr)+1; char *buf = new char[2*nLen]; WideCharToMultiByte(CP_ACP, 0, wstr, nLen, buf, 2*nLen, NULL, NULL); str = buf; delete[] buf; } else { char *pszBuffer = new char[iFileLength+1]; FileSeek(iFileHandle, 0, 0); FileRead(iFileHandle, pszBuffer, iFileLength); FileClose(iFileHandle); str=pszBuffer; delete []pszBuffer; } return str; }
http://jiamingsoft.yourblog.org/logs/144415.html
随机文章:
结晶型高纯硼粉 2008-08-14BCB中管道应用示例 2005-09-03皮肤技术研究 2004-04-24Winamp插件研究[转自CSDN] 2004-04-18LRC格式歌词分解程序 2004-04-11
收藏到:Del.icio.us





