Chinaunix首页 | 论坛 | 博客
  • 博客访问: 856430
  • 博文数量: 254
  • 博客积分: 5350
  • 博客等级: 大校
  • 技术积分: 2045
  • 用 户 组: 普通用户
  • 注册时间: 2008-06-27 13:27
文章分类

全部博文(254)

文章存档

2015年(1)

2014年(9)

2013年(17)

2012年(30)

2011年(150)

2010年(17)

2009年(28)

2008年(2)

分类: C/C++

2011-11-28 09:47:28

/* wdouble.cpp
*读取写入二进制数据,需要从ifstream和ofstream派生
*新类。由于c++中的char与byte相同,char数组可以作为
*缓冲区,保存一系列字节,表示任何二进制形式的
*值。要将一个值 写成二进制形式,程序将数值字节
*复制到输出缓冲区中,然后将这个缓冲区中的数据作为
*一系列字节写入到磁盘中。同样,要读取二进制值,
*程序将字节读取到char数组,然后将这些字节复制到相应
*相应类型变量中.
*
*/
#include
#include
#include

using namespace std;

#define FILENAME "test.dat"

class bofstream:public ofstream {
public:
    bofstream(const char * fn)
        : ofstream(fn, ios::out | ios::binary) { }

    void writeBytes(const void *, int);
    bofstream & operator << ( double );
};

//用于写入bofstream类对象的双精度型数值
bofstream & bofstream::operator << (double d)
{
    writeBytes(&d, sizeof(d));
    return * this;
}

int main()
{
    bofstream bofs(FILENAME);
    if (!bofs) {
        cerr << "Error:unable to write to " << FILENAME << endl;
        exit(1);
        }
    cout << "Writing to " << FILENAME << endl;
    double d = 314159;
    bofs << d;
    bofs << d * d;
    bofs << 9.9999999;
    d = 4.7E-8;
    bofs << d;

    return 0;
}

//将一组字节写入打开的文件
void bofstream::writeBytes(const void *p,int len)
{
    if (!p) return;
    if (len <= 0) return;
    write( (char *)p, len);
}
   
       实际上,如果只是假设二进制为字节集合,则并不需要缓冲区数组,该数组描述所有数据类型的性质。上例演示了将一些双精度值以二进制形式写入磁盘文件的基本方法

/* rdouble.cpp */
#include
#include
#include

using namespace std;

#define FILENAME "test.dat"

class bifstream:public ifstream {
public:
    bifstream (const char * fn):
        ifstream(fn, ios::in | ios::binary) { }

    void readBytes(void *, int);
    bifstream & operator >> (double &);
};

bifstream & bifstream::operator >> (double &d)
{
    readBytes(&d, sizeof(d));
    return * this;
}

int main()
{
    bifstream bifs(FILENAME);
    if (!bifs) {
        cerr << "Error: unable to open " << FILENAME << endl;
        cerr << "compile wdouble.cpp and run first\n";
        exit(1);
        }
    double d;
    long count = 0;
    cout.precision(8);
    bifs >> d;
    while(!bifs.eof()) {
        cout << ++count << ":" << d << endl;
        bifs >> d;
        }

    return 0;
}

void bifstream::readBytes(void *p, int len)
{
    if(!p) return;
    if (len <= 0) return;
    read((char *)p, len);
}




派生的bofstream和bifstream类不是读取和写入文本形式的数据,而是按本原的二进制格式处理数据。

阅读(941) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~