VC UNICODE UTF8 ANSI编码转换的疑问
想实现UNICODE、UTF8、ANSI、UTF Big endian 文件的按行读取,基本思路是:
根据
文件头 换行符
EF BB BF: UTF-8 回车换行符 单字节 0d 0a
FF FE:UNICODE 回车换行符 双字节 000d 000a
FE FF :UTF-16/UCS-2, big endian 回车换行符 双字节 0d00 0a00
ANSI:无文件头 回车换行符 单字节 0d 0a
检测文件类型,然后根据每种编码判断回车换行,按行读取。
实现函数代码如下:
CString CReadStringDlg::ReadstringFromFile(CString filepath,long linecnt)
{
CFile file(m_strPath, CFile::modeRead|CFile::shareDenyNone);
long index,cnt;
CString strRead;
wchar_t wchcr;//不同编码回车换行符
wchar_t wchlf;
int offset;
wchar_t wChLine[300];//存放每行字符
wchar_t wchtemp[2];//存放临时读取字符
TextCode tc=CheckTextFileType(m_strPath);
//每种编码的回车换行符各不相同
switch(tc)
{
case ANSI:
return ReadstringFromAnsiFile(filepath,linecnt);//ANSI文件读取已通过
case UNICODE:
offset=2*sizeof(byte);
wchcr=MAKEWORD(0x0d,0x00);//MakeWord(低、高字节顺序)
wchlf=MAKEWORD(0x0a,0x00);//UNICODE按行读取已经通过
break;
case UNICODEBIGENDIAN:
offset=2*sizeof(byte);
wchcr=MAKEWORD(0x00,0x0d);
wchlf=MAKEWORD(0x00,0x0a);
break;
case UTF8:
return ReadstringFromAnsiFile(filepath,linecnt);//当做ANSI文件来读取
}
//不同文件头 文件指针偏移不同
file.Seek(offset,CFile::begin );
cnt=0;
while(cnt<linecnt)
{
index=0;
while(TRUE)
{
file.Read(wchtemp,sizeof(wchar_t)*2);
wChLine[index++]=wchtemp[0];
wChLine[index++]=wchtemp[1];
//判断回车换行
if(wchtemp[0]==wchcr && wchtemp[1]==wchlf)
break;
//文件结束符
if(wchtemp[0]==0 && wchtemp[1]==0)
break;
}
wChLine[index]=0;
CString strtemp(wChLine,index);
strRead+=strtemp;
cnt++;
}
return strRead;
}
现在的问题是:
ANSI、UNICODE按行读取已经通过,
但是UNICODE Big endian和UTF8没有通过.
网上很多编码转换的,是我的思路错误,还是需要编码转换?
请指教!