A simple test with binary I/O in C++. It appears that after writing two values in a row, reading from the same file would concatenate the two numbers.
- In case of two integers, the first integer gets all the values, the second integers remains what it was before (For example, let a = 111, b = 234; the reading results in a = 111234, b = what-ever-old-value)
- In case of two floats, the concatenation is partial, meaning the second float still gets some value, albeit incorrect (For example, let a = 111.1, b = 234.4; the reading results in a = 111.123, b = 0.4).
I know I can use read() and write() functions of file stream to precisely control how many bytes to read, and in that case everything works. But I am just wondering if I should never use << and >>, or I was using them improperly?
#include <iostream>
#include <fstream>
using namespace std;
int main (int argc, char* argv[]){
int a = 111;
int b = 234;
cout << a << '\t' << b << endl; // print 111 234
// save
ofstream o("a.bin",ios::out|ios::binary);
o << a << b;
o.close();
// reset to test
a = -9999;
b = -9999;
// load
ifstream i("a.bin",ios::in|ios::binary);
i >> a >> b;
cout << a << '\t' << b << endl; // print 111234 -9999
return 0;
}