binfstream

以前写了一个不知道放哪去了,就重写了一个:

C++代码
  1.   
  2. class binfstream : public std::fstream   
  3. {   
  4. public:   
  5.     // 一个比较丑陋的构造函数 ^_^   
  6.     binfstream( const char* file_name, int open_mode = std::fstream::in)   
  7.         : std::fstream(file_name, open_mode | std::fstream::binary | ( (open_mode & std::fstream::out ) == 0 ? 0 : std::fstream::trunc) )   
  8.     {   
  9.   
  10.     }   
  11.   
  12.     ~binfstream()   
  13.     {   
  14.     }   
  15.   
  16.     // input   
  17.     template<typename T>   
  18.     binfstream& operator << (const T& t)   
  19.     {   
  20.         write( reinterpret_cast<const char*>(&t), sizeof T);   
  21.         return *this;   
  22.     }   
  23.   
  24.     binfstream& operator << ( const char* t)   
  25.     {   
  26.         write( t, strlen(t) + 1);   
  27.         return *this;   
  28.     }   
  29.   
  30.     binfstream& operator << ( const std::string s)   
  31.     {   
  32.         return operator << ( s.c_str());   
  33.     }   
  34.   
  35.     // output   
  36.     template<typename T>   
  37.     binfstream& operator >> (T& t)   
  38.     {   
  39.         read( reinterpret_cast<char*>(&t), sizeof T);   
  40.         return *this;   
  41.     }   
  42.   
  43.     binfstream& operator >> ( std::string &str)   
  44.     {   
  45.         char cur_char;   
  46.         while( read( &cur_char, sizeof cur_char ) )   
  47.         {   
  48.             if( cur_char == 0) break;   
  49.             str.push_back( cur_char);   
  50.         }   
  51.         return *this;   
  52.     }   
  53.   
  54. };  

使用自然是以简单为主:

C++代码
  1. #include <iostream>   
  2. #include <fstream>   
  3. #include <string>   
  4. #include "binfstream.h"   
  5.   
  6. int main( int argc, char* argv[])   
  7. {   
  8.     binfstream f( "d:\\log.txt", std::fstream::in | std::fstream::out);   
  9.   
  10.     f << 3 << std::string("hello") << "world" << 1.133;   
  11.     int i;   
  12.     std::string s1;   
  13.     std::string s2;   
  14.     double d;   
  15.   
  16.     f.seekp( std::fstream::beg);   
  17.   
  18.     f >> i >> s1 >> s2>> d;   
  19.        
  20.     std::cout << i << s1 << s2 << d;   
  21.   
  22.     return 0;   
  23. }   

其中operator << 和 >> 并没有写为友元,主要是因为我。。想 偷懒



[本日志由 ClassyK 于 2009-04-20 11:09 PM 编辑]
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: fstream
相关日志:
评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.