Hello,
I am trying to stream data to a file, and then return to the file to add further data. When I add data the second time, I then want to update the value of the second byte in the whole file. I can't seem to do this!
Here is my sample code:
Code:
int a = 1;
int b = 2;
int c = 3;
int d = 4;
int e = 5;
int f = 6;
int g = 7;
int x;
fstream out1("file.dat", ios::out | ios::binary | ios::trunc);
out1.write((char*)&a, sizeof(int));
out1.write((char*)&b, sizeof(int));
out1.write((char*)&c, sizeof(int));
out1.close();
fstream out2("file.dat", ios::out | ios::binary | ios::app);
out2.write((char*)&d, sizeof(int));
out2.write((char*)&e, sizeof(int));
out2.write((char*)&f, sizeof(int));
// Seek to the end of the first integar entry
out2.seekp(sizeof(int), ios::beg);
// Change the existing value to "7"
out2.write((char*)&g, sizeof(int));
out2.close();
fstream in("file.dat", ios::in | ios::binary);
in.seekg(0, ios::beg);
for (int i = 0; i < 10; i++)
{
in.read((char*)&x, sizeof(int));
cout << x;
}
The output I get is "1, 2, 3, 4, 5, 6", but I want to be getting "1, 7, 3, 4, 5, 6", because in "out2", I seekp to the second integar entry, and change it to "7".
I have also tried using ios::ate in the constructor for "out2", but this gives me the out put "4, 7, 6, 6, 6, 6", which is suggesting that when I create my fstream object "in", any seekg commands are relative to the beginning of the "out2" stream, rather than the "out1" stream.
Thanks for any help!