PDA

View Full Version : reading doubles from binary file



shivendra46d
21st January 2016, 08:15
Hi
I am struck with a problem of reading .bin file without using qt libraries. I am writing file with following code

double xl[200], yl[200];
int i = 0;

ofstream out ("test.bin",std::ios::binary);
if(out.is_open())
{
while( i < 100 )
{
for( double x = 0; x < 2.0 * 3.141 * 5; x += ( 3.141 / 10.0 ) )
{
yl[i] = sin(x);
qDebug()<<" y1 =="<<yl[i];
out.write((char*) &y1[i], sizeof(double));
xl[i] = x;
qDebug()<<" X1 =="<<xl[i];
out.write((char*) &xl[i], sizeof(double));
i++;

}
}
}


and m trying to read the same file but when i am reading the file the values are not same as i am writing i tried following code to read

static std::vector<char> ReadAllBytes(char const* filename)
{
ifstream ifs(filename, ios::binary|ios::ate);
ifstream::pos_type pos = ifs.tellg();

std::vector<char> result(pos);

ifs.seekg(0, ios::beg);
ifs.read(&result[0], pos);

return result;
}
void readFromFile()
{
vector<char> byteArrayfromFile = ReadAllBytes("test.bin");
qDebug()<<byteArrayfromFile.size();

union
{
char b[8];
double d;
};
for (int i=0;i<byteArrayfromFile.size()-7;i++)
{
b[7] = byteArrayfromFile.at(i+0);// 0x3F;
b[6] = byteArrayfromFile.at(i+1);//0xD1;
b[5] = byteArrayfromFile.at(i+2);//0x9B;
b[4] = byteArrayfromFile.at(i+3);//0x94;
b[3] = byteArrayfromFile.at(i+4);//0xC0;
b[2] = byteArrayfromFile.at(i+5);//0x00;
b[1] = byteArrayfromFile.at(i+6);//0x00;
b[0] = byteArrayfromFile.at(i+7);//0x00;
qDebug()<<"double"<<d;
}
}

Please help me with this

yeye_olive
21st January 2016, 10:54
I am struck with a problem of reading .bin file without using qt libraries.
Then why are you asking this question on a forum dedicated to Qt?

Your code has several serious problems.

The first question you should ask yourself is in which format data should be encoded in your file.

If you do not care about portability across architectures and readability by a human, then you can just use the memory representation of the double values directly. I believe that it is what your code is trying to do, but the part that reads the file is a horrible mess. You do not have to read the whole ifstream to a vector of chars before you reinterpret them as doubles; the underlying filebuf takes care of buffering the reads. All you have to do is read back the doubles using read(), just like you used write() to write them:


double x;
ifs.read(reinterpret_cast<char *>(&x), sizeof(double));
// TODO: check ifs' state to determine whether the read succeeded


If you care about portability, choose an architecture-dependant representation of your data and serialize to it/deserialize from it; it could be a binary representation (something like little-endian IEEE 754 binary64), or a text representation (e.g. implemented by the default >> and << operators, but some precision might be lost in the process).