CStdioFile类 一行一行读入的修改

<sayhello原创>CStdioFile类的中ReadString这个函数可以很方便的读入一行数据但是在提供的代码中有一个缺陷 如果文件最后128字节的读入有点小小的问题,如果 最后的 128个字节 你可能分成2行以上的话 系统会自动忽略 就认为是最后一行的内容,而当你明确需要全部一行一行读入那就要对源码处理下:
BOOL CMyStdioFile::ReadString(CString& rString)
{
ASSERT_VALID(this);
#ifdef _WIN32_WCE
ULONGLONG nStartPosition = CFile::GetPosition();
bool fEndOfFile = false;
#endif // _WIN32_WCE
rString = _T("");    // empty string without deallocating
const int nMaxSize = 128;
LPTSTR lpsz = rString.GetBuffer(nMaxSize);
LPTSTR lpszResult;
int nLen = 0;
for (;;)
{
#ifndef _WIN32_WCE
  lpszResult = _fgetts(lpsz, nMaxSize+1, m_pStream);
  rString.ReleaseBuffer();
  // handle error/eof case
  if (lpszResult == NULL && !feof(m_pStream))
  {
   Afx_clearerr_s(m_pStream);
   AfxThrowFileException(CFileException::genericException, _doserrno,
    m_strFileName);
  }
  // if string is read completely or EOF
  if (lpszResult == NULL ||
   (nLen = (int)ATL::lstrlen(lpsz)) < nMaxSize ||
   lpsz[nLen-1] == '
')
   break;
#else // !_WIN32_WCE
  (lpszResult);
  // Reading is not buffered, just let the internal OS buffer handle it.
  UINT nRead = CFile::Read(
   reinterpret_cast<void*>(lpsz),
   (nMaxSize)*sizeof(*lpsz) // convert from characters to bytes
   );
  
  nRead /= sizeof(*lpsz); // convert from bytes to characters
   if(nRead<=0)///这里保证文件可以读到最后一行结束
  {
   // reached end of file, terminate the string here.
   fEndOfFile = true;
   nLen = nRead;
   break;
  }
  // check for end of line character
  for(nLen = 0 ; nLen < static_cast<int>(nRead) && lpsz[nLen] != '
' ; ++nLen)
   ;
  if(lpsz[nLen]=='
')
  {
   // nLen is correct location of end of line, which should be replaced with a null terminator
   break;
  }
  
  rString.ReleaseBuffer();
#endif // !_WIN32_WCE
  nLen = rString.GetLength();
  lpsz = rString.GetBuffer(nMaxSize + nLen) + nLen;
}
#ifdef _WIN32_WCE
lpsz[nLen] = '
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值