下面进行我们的第二大类,流缓冲类。stream并不负责写或者读,毕竟如它原本的目的一样:负责格式化,存储格式化信息;当然我们还用它存储状态信息等等。stream把它的读写工作转交给stream buffer,即缓冲区类。
缓冲区类主要是围绕着位置展开操作,下面先介绍一个与位置有关的类:
/*fpos:它可以存储还原任何流中的任意文件的位置指示器所需的所有信息
* 对象的类 fpos <St> 有效地存储至少两个成员对象:
*字节偏移量,类型的 streamoff。
*转换状态,供使用的类 basic_filebuf,对象类型的 St,通常是mbstate_t。
* 它还可以存储任意文件的位置,以供类的对象 basic_filebuf,类型的fpos_t。
*对于具有有限的文件大小,但是,环境streamoff和fpos_t有时可以互换使用。
*对于不具有依赖于状态的编码的流的环境mbstate_t实际上可能是未使用。
*/
#define _Longlong __int64
typedef _Longlong streamoff;
typedef _Longlong streamsize;
typedef __int64 fpos_t;
#define _FPZ 0
#define _FPOSOFF(fp) ((long)(fp))
//定义fpos
template<class _Statetype>
class fpos//store arbitrary file position
{
typedef fpos<_Statetype> _Myt;
private:
static const _Statetype _stz;//initail conversion state
streamoff _myoff;//stream offset
fpos_t _fpos; //c file position
_Statetype _mystate; //current conversion state
public:
fpos(streamoff _off=0)
:_myoff(_off),_fpos(_FPZ),_mystate(_stz)
{//construct with stream offset
//可以进行隐式转换
}
fpos(_Statetype _state,fpos_t _fileposition)
:_myoff(0),_fpos(_fileposition),_mystate(_state)
{
//construct with conversion state and c file position
}
//此处采用了I/O接口中经常使用的策略,无参数时返回,有参数时设置
_Statetype state() const
{//return conversion state
return (_mystate);
}
void state(_Statetype _state)
{//set conversion state
_mystate=_state;
}
fpos_t seekpos() const
{
return (_fpos);
}
operator streamoff() const
{//return offset
return (static_cast<streamoff>(_myoff+_FPOSOFF(_fpos)));
}
//至此streamoff和fpos的相互转化以全部完成
streamoff operator-(const _Myt& _right) const
{
return(static_cast<streamoff>(*this)-static_cast<streamoff>(_right));
}
//遵循了+,-,+=,-=的定义法则,具体见《more effective c++》
_Myt& operator+=(streamoff _off)
{//add offset
_myoff+=_off;
return (*this);
}
_Myt& operator-=(strteamoff _off)
{//subtract offset
_myoff-=_off;
return(*this);
}
_Myt operator+(streamoff _off) const
{
_Myt _tmp=*this;
return (_tmp+=_off);
}
_Myt operator-(str