Tuesday, May 19, 2009

Write floats to binary file

1. Randomly create a series of float numbers, then write it in a binary file:

#include <iostream>
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
    srand(time(NULL));
    ofstream fout("test",ios::binary);
    ofstream fres("res.txt");
    float data;
   
    cout<<sizeof(data)<<endl;
    for(int i=0;i<100;++i)
    {
        for(int j=0;j<21;++j)
        {
            data=rand()*10.0/(RAND_MAX+1.0);
            fres<<data<<endl;
            fout.write((char*)(&data),sizeof(data));
        }
    }
   
    fout.close();
    return 0;
}

2. Decode the binary file:

#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    ifstream fin("test",ios::binary);
    ofstream fout("de.txt");
    char buffer[5];
    float *data;
   
    cout<<sizeof(data)<<endl;
   
    while(!fin.eof())
    {
        fin.read(buffer,4);
        buffer[4]='\0';
        data=(float*)buffer;
        fout<<*data<<endl;
    }
   
    return 0;
   
}

No comments:

Post a Comment