So, in the course of a numerical simulation I have noticed that if I save and load the state of my system (a large number of doubles), the following behavior of the system will be slightly different from if I just kept the info "inside the program" and didn't bother with putting it in a file for safekeeping. This is a problem, as I'd like everything to be 100% reproducible (nvm. that I am flirting with the numerical precision anyhow). I have made a lot of tests along the lines of printing the values before and after loading, and in all cases the first 16 digits are completely correct.
My theory is now that the problem occurs when converting from binary to ASCII - it is my understanding that not all 16-digit numbers can be represented exactly with 8 bytes, and vice versa. If that is the case, and some sort of rounding takes place, it would explain why I can't see the difference when printing.
So, I thought the solution would be to save and load with binary streams. But it seems that all tutorials on writing binary still assumes a cast to char - am I understanding that correctly? If so, I assume that I still pass it through the supposedly imperfect translator between binary and text, and don't solve anything.
I have been considering solutions of the type (both are taken from the wise and all-knowing internet):
ofstream outfile ("foo.in",ios_base::binary);
outfile << 1234 << " " << 5678 << " " << 9012 << endl;
outfile.close();
ifstream f("foo.in", ios_base::binary);
istream_iterator<int> b(f), e;
vector<int> v (b, e);
or
char * buffer;
long size;
ifstream infile ("test.txt",ifstream::binary);
ofstream outfile ("new.txt",ofstream::binary);
// get size of file
infile.seekg(0,ifstream::end);
size=infile.tellg();
infile.seekg(0);
// allocate memory for file content
buffer = new char [size];
// read content of infile
infile.read (buffer,size);
// write to outfile
outfile.write (buffer,size);
// release dynamically-allocated memory
delete[] buffer;
outfile.close();
infile.close();
return 0;
As usual, input will be appreciated profoundly. If I have misunderstood something about doubles or binary, I would like to be corrected as well =)