Let there be a C++ struct S
of which an instance is created and written to a binary file. Then said file is read back into the program and an instance should be created from it. How is this second part achieved?
Here is the definition of S
:
struct S {
int value;
string txt;
};
Now to create a binary file with the data for one such struct, the following function is used:
int writeStructAsBinary() {
ofstream ofs;
S s;
s.txt = "Hello World";
s.value = 10;
ofs.open("output.dat", ios::out | ios::binary);
if (!ofs.good()) { cerr << "Error opening file." << endl; return 1; }
ofs.write((char*)&s, sizeof(S));
ofs.close();
return 0;
}
I'm a bit unsure if the (char*)&s
is correct but that's what I got.
Now how can I read the data from the output.dat
file back into the program? In principle it should just be "read sizeof(S) bytes", but how do I create a Struct from the bytes? Here's my attempt?
int readAndPrintBinary() {
ifstream ifs;
ifs.open("output.dat", ios::in | ios::binary);
if (!ifs) { cerr << "Could not open file." << endl; return 1; }
ifs.seekg(0, ios::beg);
char* binaryInstance = new char[sizeof(S)];
ifs.read(binaryInstance, sizeof(S));
ifs.close();
delete binaryInstance;
return 0;
}
I'd like to now confirm s.txt
and s.value
. How can I do that?
The main program is this:
#include <iostream>
#include <string>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;
int main() {
writeStructAsBinary();
readAndPrintBinary();
}
Using reinterpret_cast
to recreate the object:
int readAndPrintBinary() {
ifstream ifs;
ifs.open("output.dat", ios::in | ios::binary);
if (!ifs) { cerr << "Could not open file." << endl; return 1; }
ifs.seekg(0, ios::beg);
char* binaryInstance = new char[sizeof(S)];
ifs.read(binaryInstance, sizeof(S));
S* s = reinterpret_cast<S*>(binaryInstance);
ifs.close();
cout << "s->txt = " << s->txt << endl;
cout << "s->value = " << s->value << endl;
delete[] binaryInstance;
return 0;
}