vs2008,在while循环为FALSE的情况下,他会报一个CArchiveException endOfFile的异常
但是我加了TRY CATCH以后,却捕捉不到这个异常
代码很简单,给出解决方案之前,麻烦先自己试一下
代码如下:
CFile file;
file.Open(m_strFileName, CFile::modeRead);
CArchive arf(&file, CArchive::load);
TRY
{
CString rString;
while(arf.ReadString(rString))
{
m_arrContent.Add(rString);
}
}
CATCH(CArchiveException, e)
{
if (e->m_cause & CArchiveException::endOfFile)
{
AfxMessageBox("You have reached the end of the file!");
}
}
END_CATCH
11 个解决方案
EOF会导致ReadString返回0,正常退出循环。
用一个变量读取arf.ReadString(rString)返回值,然后再处理.EOF应该也会有一个返回值
CATCH(CArchiveException, e)
{
if (e->m_cause == CArchiveException::endOfFile)
{
DELETE_EXCEPTION(e);
if (nRead == 0)
return NULL;
}
else
{
THROW_LAST();
}
}
mfc源代码里把eof屏蔽了?
VS2005也是一样。MS在内部被DELETE掉了。
LPTSTR CArchive::ReadString(__out_ecount_z_opt(nMax+1) LPTSTR lpsz, UINT nMax)
{
// if nMax is negative (such a large number doesn't make sense given today's
// 2gb address space), then assume it to mean "keep the newline".
int nStop = (int)nMax < 0 ? -(int)nMax : (int)nMax;
ASSERT(AfxIsValidAddress(lpsz, (nStop+1) * sizeof(TCHAR)));
if(lpsz == NULL)
return NULL;
_TUCHAR ch;
int nRead = 0;
TRY
{
while (nRead < nStop)
{
*this >> ch;
// stop and end-of-line (trailing '\n' is ignored)
if (ch == '\n' || ch == '\r')
{
if (ch == '\r')
*this >> ch;
// store the newline when called with negative nMax
if ((int)nMax != nStop)
lpsz[nRead++] = ch;
break;
}
lpsz[nRead++] = ch;
}
}
CATCH(CArchiveException, e)
{
if (e && e->m_cause == CArchiveException::endOfFile)
{
DELETE_EXCEPTION(e);
if (nRead == 0)
return NULL;
}
else
{
THROW_LAST();
}
}
END_CATCH
lpsz[nRead] = '\0';
return lpsz;
}
好像也没啥解决方案。蹭分~
调试窗口是显示的first-chance exception吧?这个没关系的。
调试窗口是显示的first-chance exception吧?这个没关系的。
用这个重载的函数
LPTSTR ReadString(
LPTSTR lpsz,
UINT nMax
);
In the version that returns an LPTSTR, a pointer to the buffer containing the text data; NULL if end-of-file was reached.