FIX: ReadString Gives Wrong Result Reading Long Strings (152319)
The information in this article applies to:
- The Microsoft Foundation Classes (MFC), when used with:
- Microsoft Visual C++, 32-bit Editions 4.0
This article was previously published under Q152319 SYMPTOMS
Reading long strings (greater than 128 characters) from a CStdioFile with
the ReadString method can result in truncated or incorrect data being
returned in the string.
CAUSE
The pointer math used in calculating buffer offsets was incorrect in the
code for CStdioFile::ReadString(CString& rString) in FILETXT.CPP.
RESOLUTION
The solution was a rewriting of the MFC code for
CStdioFile::ReadString(CString& rString). The following code is from the
MFC 4.1 source:
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;
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;
}
STATUS
Microsoft has confirmed this to be a bug in the Microsoft products listed
at the beginning of this article. This bug was corrected in the Microsoft
Foundation Classes (MFC), included with: Microsoft Visual C++, 32-bit
Edition, version 4.1.
Modification Type: | Major | Last Reviewed: | 10/24/2003 |
---|
Keywords: | kbBug kbFileIO kbfix kbNoUpdate kbVC410fix KB152319 |
---|
|