Can't read simple binary integers from a file? (C ++)

My code is just like this:

UPDATED

#include <iostream> #include <fstream> using namespace std; int main(int argc, char **argv) { ifstream r("foo.bin", ios::binary); ofstream w("foo.bin", ios::binary); int i; int ints[10] = {0,1,2,3,4,5,6,8,9}; w.write((char*)&ints, sizeof(ints)); int in_ints[10]; r.read((char*)&in_ints, sizeof(in_ints)); for(i = 0;i < 10;i++) { cout << in_ints[i] << " "; } cout << endl; return 0; } 

Now part of the recording looks successful, for example, executing the od command with 32-bit lengths (my system is 32 bits) will display the correct sequence, including a hexadecimal dump.

However, I get random sequences of such and negative integers that should not happen (they are separated and basically zeros, since my integers are small, the signed bits should not be included.)

You see why my reading method did not work when it really is the opposite of my writing method?

+8
source share
3 answers

try w.flush() or w.close() before r.read . the problem is when you write it, as a rule, it buffers the text and does not save it in a file. therefore there is nothing real in the file for r.read .

+7
source

This code:

 #include <iostream> #include <fstream> using namespace std; int main() { { ofstream w( "foo.txt" ); int ints[10] = {0,1,2,3,4,5,6,8,9}; w.write((char*)&ints, sizeof(ints)); } { ifstream r( "foo.txt" ); int in_ints[10]; r.read((char*)&in_ints, sizeof(in_ints)); for( int i = 0; i < 10; i++) { cout << in_ints[i] << " "; } } } 

prints:

0 1 2 3 4 5 6 8 9 0

Note that some numbers are missing in your initialization.

+6
source

Data written to a file is not necessarily displayed in other streams (in the same process or not) until the file is closed or at least turns red. And if the file "foo.bin" does not exist before the program starts, opening it for reading will not work (and therefore all further use will not be op). Your program violates one of the basic rules of programming: if something can fail, always check to see if it continues before. You do not check the results of your I / O.

I could also add that reading and writing data in this way is very, very fragile and, as a rule, can only be guaranteed to work in the same process - even recompiling with a different version of the compiler or different compiler options can lead to the presentation of the change data , with results that you cannot read earlier. Of course, in the case of int arrays, this is very unlikely unless you change the architecture of the machines. But in general, if you need to re-read the data in the future, this technique is best avoided. ( (char*) reinterpret_cast , and as we know that reinterpret_cast is a very strong signal that there is a portability problem.)

+1
source

All Articles