1

So I have this code, pretty straightforward:

struct Item{
int x;
};


int main(){

    ofstream dat("file.bin", ios::binary);

    Item chair;

    for (int i = 0; i < 20; i++) {
           chair.x = i;
           dat.write((char*)&chair, sizeof(Item));
    }


ifstream dat2("file.bin", ios::binary);

for (int i = 0; i < 20; i++) {
    dat2.read((char*)&chair, sizeof(Item));
    cout << chair.x << endl;
}


return 0; }

When I run this code, even though I always set the chair.x to the value of i, when I read the entries in the second for loop, every .x value that is read is 19. Here is the result, since I'm bad at explaining:

Code result it should however be 0, 1, 2, ... 19. Where am I getting this wrong?

aakk
  • 334
  • 4
  • 15
  • 3
    Try to close ostream before opening file for reading – Elalfer Jun 19 '16 at 19:16
  • @Elalfer I feel like an idiot. It's working now. Thanks! – aakk Jun 19 '16 at 19:17
  • In the future, check for I/O errors. This would have let you know that you were wrong about "every .x value that is read is 19" and that in fact nothing at all was being read. – Ben Voigt Jun 19 '16 at 19:33

1 Answers1

2

I see, you are reading and writing the same file; why don't you flush or close the stream before reading the file again. See A good explanation to buffering in streams

int main(){

    ofstream dat("file.bin", ios::binary);

    Item chair;

    for (int i = 0; i < 20; i++) {
           chair.x = i;
           dat.write((char*)&chair, sizeof(Item));
    }
    dat.flush();      //Add this here
    //dat.close();    //or this


    ifstream dat2("file.bin", ios::binary);

    for (int i = 0; i < 20; i++) {
        dat2.read((char*)&chair, sizeof(Item));
        cout << chair.x << endl;
    }


return 0;
}
Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68