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:
it should however be 0, 1, 2, ... 19. Where am I getting this wrong?
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;
}