binfstream
作者:ClassyK 日期:2009-04-20
以前写了一个不知道放哪去了,就重写了一个:
C++代码
- class binfstream : public std::fstream
- {
- public:
- // 一个比较丑陋的构造函数 ^_^
- binfstream( const char* file_name, int open_mode = std::fstream::in)
- : std::fstream(file_name, open_mode | std::fstream::binary | ( (open_mode & std::fstream::out ) == 0 ? 0 : std::fstream::trunc) )
- {
- }
- ~binfstream()
- {
- }
- // input
- template<typename T>
- binfstream& operator << (const T& t)
- {
- write( reinterpret_cast<const char*>(&t), sizeof T);
- return *this;
- }
- binfstream& operator << ( const char* t)
- {
- write( t, strlen(t) + 1);
- return *this;
- }
- binfstream& operator << ( const std::string s)
- {
- return operator << ( s.c_str());
- }
- // output
- template<typename T>
- binfstream& operator >> (T& t)
- {
- read( reinterpret_cast<char*>(&t), sizeof T);
- return *this;
- }
- binfstream& operator >> ( std::string &str)
- {
- char cur_char;
- while( read( &cur_char, sizeof cur_char ) )
- {
- if( cur_char == 0) break;
- str.push_back( cur_char);
- }
- return *this;
- }
- };
使用自然是以简单为主:
C++代码
- #include <iostream>
- #include <fstream>
- #include <string>
- #include "binfstream.h"
- int main( int argc, char* argv[])
- {
- binfstream f( "d:\\log.txt", std::fstream::in | std::fstream::out);
- f << 3 << std::string("hello") << "world" << 1.133;
- int i;
- std::string s1;
- std::string s2;
- double d;
- f.seekp( std::fstream::beg);
- f >> i >> s1 >> s2>> d;
- std::cout << i << s1 << s2 << d;
- return 0;
- }
其中operator << 和 >> 并没有写为友元,主要是因为我。。想 偷懒
评论: 0 | 引用: 0 | 查看次数: -
发表评论
上一篇
下一篇

文章来自:
Tags:
相关日志: