This example serve as an inspiration in case you want to write an array of variable size of structures into a binary file and later read them.
Like a vector
of structs
that has string
members, as follows.
struct Data {
std::string str;
int value;
};
std::vector<Data> myCompicatedData;
Use ofstream
to write your data then open it with an ifstream
. Writing and reading depends on the type of the data:
- For binary data (like
double
orfloat
) use thestd::ofstream::write
method - For plain data (like
bool
,int
,uint32_t
) use theoperator<<
- For writing
std::string
use theoperator<<
followed by a delimiter character, and read using thegetline
method
- You must define a
char
that will be the delimiter, and under no circumstances present in thestring
member - Maximum length of one
string
must be defined - The
structure
should not end with thestring
It is not possible to write to binary then read structures only containing string
members (constraint #3).
Writing data from raw user input is not recommended as it
a) might contain the delimiter (constraint #1)
b) might be 'infinite' long (constraint #2)
therefore invalidating the read.