CStdioFile的一个小Bug

编程读写文件很多人用CStdioFile,不为别的,只是这个简单,函数少。CStdioFile::ReadString把打开的文件读入,CStdioFile::WriteString写内容到文件,具体参看MSDN了。下面是个简单的例子:

 CStdioFile Inputfile,  Outputfile;
 CFileException FileExc;
 UINT nOpenFlags;
 CString s;
 nOpenFlags = CFile::modeRead;
 if (!Inputfile.Open("In.txt", nOpenFlags, &FileExc))
 {
      FileExc.ReportError();
      return;
 }
 nOpenFlags = CFile::modeWrite | CFile::modeCreate;
 if (!Outputfile.Open("Out.txt", nOpenFlags, &FileExc))
 {
      FileExc.ReportError();
      return;
 }
 while (Inputfile.ReadString(s))
      Outputfile.WriteString(s+'/n');
 Inputfile.Close();
 Outputfile.Close();

很多时候上面那个例子没有任何问题。但偶然一次机会我发现了一个问题,当你In.txt文件正好包含的字节数为128的整数倍,那么Out.txt就不会有内容,因为ReadString( )返回的是FALSE。怎么会这样呢?看看CStdioFile::ReadString(CString& rString)是如何实现的,看到那个红字体标注的了吗?看到了你也就明白了怎么回事了。MS编写这个库的人怎么会出现这样的疏忽呢?搞不明白!建议以后还是判断rString是否empty来的妥当些。

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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值