第一种方式:
CFile file;
CString str_dates;
char buf[1024];
memset(buf,0,1024);
try
{
if(! file.Open(strFileName,CFile::modeRead))
{
AfxMessageBox(L"打开文件失败!");
return;
}
file.Read(buf,sizeof(buf));
str_dates = buf;
file.Close();
}
catch (CFileException* e)
{
CString str ;
str.Format(L"读取树型结构文本数据失败的原因:%d",e->m_cause);
file.Abort();
e->Delete();
}
这种方式,是确定了读取内容的大小。当文件较大时、或者不确定文件的大小的时候,这种声明具体内容大小的,会有些局限性。
可以使用第二种方式:
根据文件的大小申请空间
CFile file;
CString str_dates;
try
{
if(! file.Open(strFileName,CFile::modeRead))
{
AfxMessageBox(L"打开文件失败!");
return;
}
LONG nLengths = file.GetLength();
char *buf ;
buf = new char[nLengths + 1];
memset(buf,0,nLengths+1);
buf[nLengths] = 0;
file.Read(buf,nLengths);
str_dates = buf;
file.Close();
delete[] buf;
}
catch (CFileException* e)
{
CString str ;
str.Format(L"读取树型结构文本数据失败的原因:%d",e->m_cause);
file.Abort();
e->Delete();
}