Problem on reading binary files
Aug 31, 2017 at 7:36pm UTC
I'm trying to create and read a simple binary file but instead of displaying from 1 to 10 it displays 10 0's.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char name[20];
cin >> name;
ofstream create(name);
int vetor[] = {1,2,3,4,5,6,7,8,9,10};
for (int i = 0; i < 10; i++){
create.write(reinterpret_cast <char *> (&vetor[i]), sizeof (int ));
}
ifstream reading(name);
int * arr = new int [10];
for (int i = 0; i < 10; i++){
reading.read(reinterpret_cast <char *> (&arr[i]), sizeof (int ));
}
for (int i = 0; i < 10; i++){
cout<<arr[i]<<' ' ;
}
delete [] arr;
return 0;
}
Aug 31, 2017 at 7:41pm UTC
You probably need to close the file between your write and read operations.
Aug 31, 2017 at 7:44pm UTC
It worked! Thanks, but why do I need to close them?
Aug 31, 2017 at 8:12pm UTC
Because your operating system may lock the file for exclusive access for the output stream.
You also should be checking that the stream opening succeeds and that the write/read operations also succeed.
Sep 1, 2017 at 3:11am UTC
Adding
create.flush();
after writing to the file could do it. It will send whatever is stored in the output buffer to the physical file. When the file is closed the same buffer flushing is done, as well as releasing the resource.
If you are dealing with binary files, its a good idea to open in binary mode:
ofstream create(name, ios::binary );
and similarly for the
ifstream
.
Last edited on Sep 1, 2017 at 3:14am UTC
Topic archived. No new replies allowed.