Why does my array seem to double in size the second time I write it to a file?

Hello,

Why does my array seem to double in size after writing to the file a second time in the following code:

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
35
36
37
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    int array[2][5]=
    {
        {1,1,1,1,0},
        {0,0,0,1,1}
    };
    
    int array2[2][5]=
    {
        {0,0,1,1,1},
        {1,0,0,1,0}
    };
    
    fstream file("brainfart.bin",ios::in|ios::out|ios::binary|ios::app);
    
    file.write(reinterpret_cast<char*>(array),sizeof(array));
    
    cout<<file.tellg()<<endl;
    cout<<file.tellp()<<endl;
    
    file.seekg(0);
    file.seekp(0);
    
    file.write(reinterpret_cast<char*>(array2),sizeof(array2));
    
    cout<<file.tellg()<<endl;
    cout<<file.tellp()<<endl;
    
    return 0;
    
    
}


The first batch of "cout" statements return 40, but the second, which I would also expect to return 40, return 80. Why is this?

Thank you!
The first batch of "cout" statements return 40, but the second, which I would also expect to return 40, return 80. Why is this?
ios::app
In my thinking, the position returned by tellp or tellg should only go to 40 the second time I write because after I set seekp and seekg to 0, it will only write for another 40 bytes, and so although the entire file would contain 80 bytes, the position would be at 40. But if that's not how ios::app works, is there a different flag that works this way? Thank you.
Last edited on
For me the program prints 40 four times.

40
40
40
40
Topic archived. No new replies allowed.