MFC Traps and Pitfalls[转贴]
本贴转自:www.allaboutprogram.com/bb,原作者:pora
-----------------------------------------------------------
pora
加入于: 2002-09-03
文章: 414
点数: 550
发表于: 星期二 二月 25, 2003 10:19 pm 发表主题: MFC Traps and Pitfalls
--------------------------------------------------------------------------------
我开这个帖子旨在抛砖引玉,并且这里很多帖子是阳春白雪,我们也谈点实际应用。
先说一个:
CStdioFile::ReadString
代码:
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;
}
请注意那句
const int nMaxSize = 128;
当你文件中一行的长度超过128的时候,这个函数会出错。