六.字符串的读写 ①CArchive提供的WriteString和ReadString
字符串写 void CArchive::WriteString(LPCTSTR lpsz)
{
ASSERT(AfxIsValidString(lpsz));
Write(lpsz, lstrlen(lpsz) * sizeof(TCHAR)); //调用Write,将字符串对应的一段
数据写入
}
字符串读(读取一行字符串) LPTSTR CArchive::ReadString(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)));
_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-> m_cause == CArchiveException::endOfFile)
{
DELETE_EXCEPTION(e);
if (nRead == 0)
return NULL;
}
else
{
THROW_LAST();
}
}
END_CATCH
lpsz[nRead] = ''\0'';
return lpsz;
}
ReadString到CString对象,可以多行字符 BOOL CArchive::ReadString(CString& rString)
{
rString = &afxChNil; // empty string without deallocating
const int nMaxSize = 128;
LPTSTR lpsz = rString.GetBuffer(nMaxSize);
LPTSTR lpszResult;
int nLen;
for (;;)
{
lpszResult = ReadString(lpsz, (UINT)-nMaxSize); // store the newline
rString.ReleaseBuffer();
// 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;
}