I have a binary file that contains numbers of a type double.
The example input file is available here: http://www.bobdanani.net/download/A.0.0
I would like to read the file and print the numbers in it.
This is what I have done:
char* buffer;
int length;
string filename = "A.0.0";
ifs.open (filename.c_str(), ios::in | ios::binary);
// get length of file:
ifs.seekg (0, ios::end);
length = ifs.tellg();
ifs.seekg (0, ios::beg);
// allocate memory:
buffer = new char [length];
// read data as a block:
ifs.read (buffer,length);
ifs.close();
cout.write (buffer,length);
cout << buffer << endl;
delete[] buffer;
I have also tried to use a type casting to double when printing the number, but I got strange characters. What is the best way to do this? I need the data of this binary file as an input to a function for a parallel program. But this is out of the scope of this question.
While I could be wrong, since you said the number is separated by a tab/space, I’m willing to be this is actually ASCII data, and not raw binary data. Therefore the best way to work with the floating point value would be to use the
operator>>on theifstreamobject and then push that into adouble. That will do an automatic conversion of the input value into a double, where-as what you’ve done will merely copy the character bytes that compose a floating point value, but are not a floating point value themselves. Additionaly, if you were trying to output your buffer like a string, you haven’t explicitly null-terminated it, so it’s going to keep reading up the stack until it encounters a null-terminator or you get a segmentation fault due to accessing memory the OS isn’t allowing you to access off the top of the stack. But either way, in the end, your buffer won’t be a representation of adoubledata-type.So you would have something like: