Stream操作注意事项
1. 流状态判断操作:
while(is.good()&&!is.eof())
|
改为如下写法就行了
因为如果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。