编程读写文件很多人用CStdioFile,不为别的,只是这个简单,函数少。CStdioFile::ReadString把打开的文件读入,CStdioFile::WriteString写内容到文件,具体参看MSDN了。下面是个简单的例子:
CStdioFile Inputfile, Outputfile;
CFileException FileExc;
UINT nOpenFlags;
CString s;
nOpenFlags = CFile::modeRead;
if (!Inputfile.Open("In.txt", nOpenFlags, &FileExc))
{
FileExc.ReportError();
return;
}
nOpenFlags = CFile::modeWrite | CFile::modeCreate;
if (!Outputfile.Open("Out.txt", nOpenFlags, &FileExc))
{
FileExc.ReportError();
return;
}
while (Inputfile.ReadString(s))
Outputfile.WriteString(s+'/n');
Inputfile.Close();
Outputfile.Close();
很多时候上面那个例子没有任何问题。但偶然一次机会我发现了一个问题,当你In.txt文件正好包含的字节数为128的整数倍,那么Out.txt就不会有内容,因为ReadString( )返回的是FALSE。怎么会这样呢?看看CStdioFile::ReadString(CString& rString)是如何实现的,看到那个红字体标注的了吗?看到了你也就明白了怎么回事了。MS编写这个库的人怎么会出现这样的疏忽呢?搞不明白!建议以后还是判断rString是否empty来的妥当些。
BOOL CStdioFile::ReadString(CString& rString)
{
ASSERT_VALID(this);
rString = &afxChNil; // empty string without deallocating
const int nMaxSize = 128;
LPTSTR lpsz = rString.GetBuffer(nMaxSize);
LPTSTR lpszResult;
int nLen = 0;
for (;;)
{
lpszResult = _fgetts(lpsz, nMaxSize+1, m_pStream);
rString.ReleaseBuffer();
// handle error/eof case
if (lpszResult == NULL && !feof(m_pStream))
{
clearerr(m_pStream);
AfxThrowFileException(CFileException::generic, _doserrno,
m_strFileName);
}
// if string is read completely or EOF
if (lpszResult == NULL ||
(nLen = lstrlen(lpsz)) < nMaxSize ||
lpsz[nLen-1] == '/n')
break;
nLen = rString.GetLength();
lpsz = rString.GetBuffer(nMaxSize + nLen) + nLen;
}
// remove '/n' from end of string if present
lpsz = rString.GetBuffer(0);
nLen = rString.GetLength();
if (nLen != 0 && lpsz[nLen-1] == '/n')
rString.GetBufferSetLength(nLen-1);
return lpszResult != NULL;
}