Problem on reading binary files

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;
}
You probably need to close the file between your write and read operations.

It worked! Thanks, but why do I need to close them?
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.

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
Topic archived. No new replies allowed.