CString strFilePath;
CFile mFile;
if(!mFile.Open(L“Pos.txt”,CFile :: modeRead | CFile :: typeBinary))
{
MessageBox(_T(“无法打开文件:”)+ strFilePath,_T(“错误”),MB_ICONERROR | MB_OK );
PostQuitMessage(0);
}
BOOL m_isUnicode = FALSE;
BOOL m_isUTF_8Code = FALSE;
字节头[3]; //获取头部内容
字符串strContents; //文件内容
UINT FileSize; //文件大小
char * buf; // temp
mFile.Read(head,3);
//判断txt中数据是Unicode格式还是UTF-8还是ANSI格式
if((head [0] == 0xff && head [1] == 0xfe)||(head [0] == 0xfe && head [1] == 0xff))//测试文件是Unicode?
{
m_isUnicode = true;
}
if((head [0] == 0xef && head [1] == 0xbb && head [2] == 0xbf)||(head [0] == 0xbf && head [1] == 0xbb && head [2] == 0xef))//测试文件是UTF-8 ??
{
m_isUTF_8Code = true;
}
if(m_isUTF_8Code)//读取UTF-8文件
{
FileSize =(UINT)mFile.GetLength();
buf = new char [FileSize];
mFile.Seek(3,CFile :: begin); // 0xefbbbf
mFile.Read(buf,FileSize);
int size = MultiByteToWideChar(CP_UTF8,0,buf,FileSize + 1,NULL,0);
wchar_t * pWideChar = new wchar_t [size + 1];
MultiByteToWideChar(CP_UTF8,0,buf,FileSize + 1,pWideChar,size);
// strContents = CString(pWideChar).GetBuffer(0);
删除[] buf;
删除[] pWideChar;
}
else if(m_isUnicode)//读取Unicode文件;
{
int i = 1;
wchar_t wch; // for unicode
wchar_t wstr [300]; // for unicode
memset((void *)wstr,0,sizeof(char)*(2 * 300));
mFile.Seek(2,CFile :: begin); // 0xfffe
while(mFile.Read((char *)&wch,2)> 0)
{
if(wch == 0x000D)// by line
{
//更改为ANSI
int nLen = i;
buf = new char [2 * nLen];
memset((void *)buf,0,sizeof(char)*(2 * nLen));
WideCharToMultiByte(CP_ACP,0,wstr,-1,buf,2 * nLen,NULL,NULL);
buf [2 * nLen - 1] ='\ 0';
// buf就是读取的txt中每行的数据
strContents + = buf;
删除[] buf;
i = 0;
}
else
{
wstr [i ++] = wch;
CString str = wstr;
}
}
}
否则//读取ANSI文件
{
文件大小=(UINT)mFile.GetLength();
buf = new char [FileSize];
while(mFile.Read(buf,FileSize)> 0)
{
strContents = buf;
}
delete [] buf;
}
mFile.Close();