- /* bstream.h */
-
#include <iostream>
-
#include <fstream>
-
-
using namespace std;
-
-
// Binary output file stream
-
-
class bofstream:public ofstream {
-
public:
-
bofstream(const char *fn)
-
:ofstream(fn, ios::out|ios::binary) { }
-
void writeBytes(const void *, int);
-
template < class T>
-
bofstream & operator<< (const T & data);
-
};
-
-
template <class T>
-
bofstream & bofstream::operator<< (const T & data) //调用时会带this指针,因为返回了bofstream对象,与下面的重载区别
-
{
-
writeBytes(&data, sizeof(data));
-
return * this;
-
}
-
-
//Binary input file stream
-
class bifstream:public ifstream {
-
public:
-
bifstream(const char *fn)
-
:ifstream(fn, ios::in|ios::binary) { }
-
void readBytes(void *, int);
-
template <class T>
-
bifstream & operator>> (T & data);
-
};
-
-
template <class T>
-
bifstream & bifstream::operator>> (T & data)
-
{
-
readBytes(&data, sizeof(data));
-
return * this;
-
}
/* bstream.cpp */
#include "bstream.h"
void bofstream::writeBytes(const void * p, int len)
{
if (!p) return;
if (len <= 0) return;
write((char *)p, len);
}
void bifstream::readBytes(void *p,int len)
{
if(!p) return;
if (len <= 0) return;
read((char *)p, len);
}
使用了模板函数,其它均和前例保持一样。。
/* tbdouble.cpp */
/* 基于模板类的测试实例*/
#include
#include
#include "bstream.h"
using namespace std;
#define FILENAME "tbdouble.dat"
int main()
{
//construct binary output file
bofstream bofs(FILENAME);
if (!bofs) {
cerr << "Error:unable to write to " << FILENAME < exit(1);
}
//write values and close file
double d = 3.14159;
bofs << d << d * d << d * d * d;
bofs.close();
//construct binary input file
bifstream bifs(FILENAME);
if (!bifs) {
cerr << "Error: uanble to open " << FILENAME << endl;
exit(2);
}
//Read and display values from file
int count = 0;
cout.precision(8);
bifs >> d; // reading data by sizeof(d) byte
while (!bifs.eof()) {
cout << ++count << ": " << d << endl;
bifs >> d;
}
return 0;
}