I have 2 c++ code: one is for write data into a binary file, another is for read that file.
write.cpp
code is as below:
#include
The only way that comes to mind is to write the following data separately:
and read them separately.
Create functions to write/read an instance of Data
such that they are aware of each other's implementation strategy.
std::ostream& write(std::ostream& out, Data const& data)
{
size_t len = data.name.size();
out.write(reinterpret_cast(&len), sizeof(len));
out.write(data.name.c_str(), len);
out.write(reinterpret_cast(&data.age));
return out;
}
std::istream& read(std::istream& in, Data& data)
{
size_t len;
in.read(reinterpret_cast(&len), sizeof(len));
char* name = new char[len+1];
in.read(name, len);
name[len] = '\0';
data.name = name;
delete [] name;
in.read(reinterpret_cast(&data.age));
return in;
}
and use them similarly to your first approach.
Instead of using
people.write(reinterpret_cast(&person),sizeof(person));
use
write(people, person);
Instead of using
people.read(reinterpret_cast(&person),sizeof(person));
use
read(people, person);