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
doubleorfloat) use thestd::ofstream::writemethod - For plain data (like
bool,int,uint32_t) use theoperator<< - For writing
std::stringuse theoperator<<followed by a delimiter character, and read using thegetlinemethod
- You must define a
charthat will be the delimiter, and under no circumstances present in thestringmember - Maximum length of one
stringmust be defined - The
structureshould 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.