读取文本文档【自动区分文本格式】

16 篇文章 2 订阅
4 篇文章 0 订阅
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;

}
调用方法就不用多说了吧,直接输入一个文本文件路径即可,返回的是文本文档的内容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值