stream流操注意事项

Stream 操作注意事项
 
 
1.        流状态判断操作:

while(is.good()&&!is.eof())
 

 
 

改为如下写法就行了

while(is.good())
 

 
 

因为如果 is.eof() 为真, is.good() 肯定为 False
 
2.        避免使用 readline ,请改用 read 方法。原因如下:
 
readline 会循环地进行判断,严重影响效率。从如下代码实现中你就可以看出 readline 将会是极低效的读取。
 

_Myt& read(_E *_S, streamsize _N)
              {iostate _St = goodbit;
              _Chcount = 0;
              const sentry _Ok(*this, true);
              if (_Ok)
                     {_TRY_IO_BEGIN
                     const streamsize _M = rdbuf()->sgetn(_S, _N);
                     _Chcount += _M;
                     if (_M != _N)
                            _St |= eofbit | failbit;
                     _CATCH_IO_END }
              setstate(_St);
              return (*this); }
      

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

_Myt& getline(_E *_S, streamsize _N, _E _D)
              {iostate _St = goodbit;
              _Chcount = 0;
              const sentry _Ok(*this, true);
              if (_Ok && 0 < _N)
                     {int_type _Di = _Tr::to_int_type(_D);
                     _TRY_IO_BEGIN
                     int_type _C = rdbuf()->sgetc();
                     for (; ; _C = rdbuf()->snextc())
                            if (_Tr::eq_int_type(_Tr::eof(), _C))
                                   {_St |= eofbit;
                                   break; }
                            else if (_C == _Di)
                                   {++_Chcount;
                                   rdbuf()->stossc();
                                   break; }
                            else if (--_N <= 0)
                                   {_St |= failbit;
                                   break; }
                            else
                                   {++_Chcount;
                                   *_S++ = _Tr::to_char_type(_C); }
                     _CATCH_IO_END }
              *_S = _E(0);
              setstate(_Chcount == 0 ? _St | failbit : _St);
              return (*this); }
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

3.        不要重载操作符
std::istream& operator >> (std::istream& is, std::string& str); 这与 C++ 标准库中定义的操作符是有潜在冲突的,一不小心,就会有混淆了两者的调用。但目前暂时将错就错了。
 
4.        显式地调用 std::operator>> 操作。
3 所描述,如果你害怕误用操作符操作,请显式地调用流操作符。
如: std::operator >>(fs,str); 或者 PDF_Base::operator>>(fs,str)
 
5.        决对不要有这种用法, 100% 死机。

char szbuf[_MAX_LEN] = {0};
is>>szbuf;
 

 
 

原因很简单,内存越界。
 
6.        PDF 文件是二进制文件,打开操作需要标明 std::ios::binary
 
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值