How would I write/read data to a file in binary, if I also have to define how to save my data?
I'm attempting to save some simple data structures out to a file in binary.
For example, I have a vector of structs like this:
struct Vertex
{
x;
y;
z;
}
std::vector<Vertex> vertices;
I want to save this vector out to a file in binary.
I know how to output it using ifstream and ostream using the << and >> operators, which can be overloaded to handle my data, but they can't output binary.
I also know how to use .write() to write in binary, but the issue there is that I can't find a way to overload what I need, in order to handle my data.
Here is an answer to a similar question. While this is ok in your case, be aware that if you are using pointers in your struct, this will not work.
The pointer means : "There is relevant data loaded in this other memory segment", but really, it only contains the address of the memory. Then the write operation will save this memory location. When you will load it back, there is very little chance that the memory still holds the information you want.
What people usually do is create a serialization mechanism. Add a method to your struct, or write another function that takes your struct as a parameter and outputs a char* array containing the data in a special format you decide. You will also need the opposite function to read from a file and recreate a struct from binary data. You should take a look at boost::serialization which handles this very common programming problem.
One way of doing it (not necessarily the best) is to write the data, using whatever binary write function you choose, eg
write(fd,data,size);
But pass the "data" as the struct.
eg
Vertex data;
data.x = 0;
etc...
write(fd,(char*)&data,sizeof(data));
which will treat the struct as an array of characters, and then write them to the file. Reading it back in should be the reverse of the above.
Note that there is not really a nice way to do this with vectors (which are dynamically allocated and my have strange things in strange places in memory), so I recommend an array of structs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With