I am trying to replace a double value that is on the 32th byte in the binary file. In the below setup, the size of MyStruct
is 24 bytes. Therefore, the 32th byte in file should be the Weight
member variable of the 2nd struct. Right now when I execute, I am getting the strange output. I am expecting my 2nd struct to have the new weight value of 250 instead of 200:
#include <iostream>
#include <fstream>
using namespace std;
struct MyStruct
{
int Grade;
double Weight;
char Gender;
};
int main()
{
MyStruct* lStruct = new MyStruct{ 1, 100, 'M' };
MyStruct* lStruct2 = new MyStruct{ 2, 200, 'F' };;
fstream InFile;
InFile.open("test.txt", ios::in | ios::out | ios::binary);
InFile.write(reinterpret_cast<char*>(lStruct), sizeof(MyStruct));
InFile.write(reinterpret_cast<char*>(lStruct2), sizeof(MyStruct));
InFile.seekp(32, ios::beg);
double Weight = 250;
InFile.write(reinterpret_cast<char*>(&Weight), sizeof(double));
InFile.seekg(0, ios::beg);
InFile.read(reinterpret_cast<char*>(lStruct), sizeof(MyStruct));
InFile.seekg(24, ios::beg);
InFile.read(reinterpret_cast<char*>(lStruct2), sizeof(double));
cout << lStruct->Grade<< endl;
cout << lStruct->Weight << endl;
cout << lStruct->Gender<< endl;
cout << endl;
cout << lStruct2->Grade<< endl;
cout << lStruct2->Weight << endl;
cout << lStruct2->Gender<< endl;
cout << endl;
return 0;
}
Output:
1
100
M
2
200
F
What is the problem?
Bonus question: is seekp(32, ios::beg)
equivalent to seekp(-16, ios::end)
? (can I use negative away-from end)?