- //
- // StreamUtils.h
- // 流的一些实用类
- // Author : zhanlc
- // Date : 2003/9/10
- #ifndef __StreamUtils_H__
- #define __StreamUtils_H__
- /**
- * 流配接器
- */
- template <class TStream>
- class TStreamAdapter
- {
- protected :
- /**
- * 具体的流
- */
- TStream* m_pStream;
- public :
- /**
- * 构造函数
- */
- TStreamAdapter(TStream* strm ) : m_pStream(strm)
- {
- };
- /**
- * 输出函数
- */
- template <class T>
- TStreamAdapter& operator<<( const T& t )
- {
- ASSERT( m_pStream );
- m_pStream->Write( &t, sizeof(T) );
- return *this;
- };
- //template <>
- TStreamAdapter& operator<<( const CString& str )
- {
- SaveComplex(str);
- return *this;
- }
- //template <>
- TStreamAdapter& operator<<( const TCHAR*& str )
- {
- SaveComplex( str );
- return *this;
- }
- /**
- * 输入函数
- */
- template <class T>
- TStreamAdapter& operator>>( T& t)
- {
- ASSERT( m_pStream );
- m_pStream->Read( &t, sizeof(T) );
- return *this;
- };
- //template <>
- TStreamAdapter& operator>>( CString& str )
- {
- ASSERT( m_pStream );
- LoadComplex(str);
- return *this;
- }
- public :
- /**
- * 保存简单类型
- */
- template <class T>
- void SaveSimple( T t )
- {
- m_pStream->Write( &t, sizeof(T) );
- }
- /**
- * 输出字符串
- */
- void SaveComplex( const TCHAR* szContent )
- {
- ASSERT( m_pStream );
- // write the length
- int nLen = _tcslen(szContent);
- operator<<(nLen);
- // write the content
- m_pStream->Write( szContent, nLen );
- }
- /**
- * 输出字符串
- */
- void SaveComplex( const CString& szContent )
- {
- SaveComplex( (const TCHAR*)szContent );//operator<<( (const TCHAR*)szContent );
- }
- /**
- * 输入简单类型
- */
- template <class T>
- void LoadSimple( T& t)
- {
- m_pStream->Read( &t, sizeof(T) );
- }
- /**
- * 输入字符串
- */
- void LoadComplex( CString& str )
- {
- ASSERT( m_pStream );
- int nLen;
- operator>>(nLen);
- ASSERT( nLen >= 0 );
- if ( nLen == 0 )
- return ;
- // 读入字符
- TCHAR strBuf[256];
- TCHAR* pBuf = strBuf;
- if ( nLen > sizeof(strBuf)/sizeof(TCHAR) - 1 )
- pBuf = new TCHAR[nLen+1];
- pBuf[nLen] = TCHAR(' ');
- m_pStream->Read( pBuf, nLen );
- // assign
- str = pBuf;
- if ( nLen > sizeof(strBuf)/sizeof(TCHAR) - 1 )
- delete [] pBuf;
- }
- };
- #endif