CString ReadFile2Txt(const CString strFilePath)
{
CFile fileText; CFileException fileException;
if (fileText.Open(strFilePath,CFile::modeRead,&fileException) == FALSE)
{
ASSERT (FALSE);
// 打开文件错误,识别什么错误。注:以下有我自定义常量,事件可以更改为自己的或者删除
switch (fileException.m_cause)
{
case CFileException::fileNotFound: return SetLastError(ERR_FILENOTFOUND),NULL;break;
case CFileException::accessDenied: return SetLastError(ERR_ACCESSDENIED),NULL;break;
case CFileException::sharingViolation: return SetLastError(ERR_SHARINGVIOLATION),NULL;break;
default:return SetLastError(ERR_UNKNOW),NULL;break;
}
}
CString strFile = TEXT("");
ULONG nFileSize = (ULONG)fileText.GetLength();
// 定义保存读取内容的数组,大小为文本文件长度
char* pContent=(char*)calloc(nFileSize+1,sizeof(char));
// UTF-8文件,文件的前三个字节是:EFBBBF。
unsigned long head(3);
if (fileText.Read(&head,3) != 3)
{
fileText.Close();
return SetLastError(ERR_READFILE),NULL;
}
// 如果文件的前三个字节不是0xEFBBBF,则说明为正常文本文档
fileText.Seek(head == 0xEFBBBF ? 3:0,CFile::current);
ULONG nReadSize = nFileSize - (head == 0xEFBBBF ? 0:3);
if (fileText.Read(pContent,nReadSize) != nReadSize)
{
ASSERT(FALSE),fileText.Close();
SetLastError(ERR_READFILE);
return strFile;
}
fileText.Close();
if (head == 0xEFBBBF)
{
// 将UTF-8转化为ANSI编码
int n=MultiByteToWideChar(CP_UTF8,0,pContent,nFileSize+1,NULL,0);
wchar_t* pWideChar=(wchar_t*)calloc(n+1,sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8,0,pContent,nFileSize+1,pWideChar,n);
strFile=CString(pWideChar);
free(pWideChar);
}else
{
strFile = pContent;
}
free(pContent);
SetLastError(ERR_NONE);
return strFile;
}
调用方法就不用多说了吧,直接输入一个文本文件路径即可,返回的是文本文档的内容
读取文本文档【自动区分文本格式】
最新推荐文章于 2021-05-18 05:28:25 发布