As usual I made a mistake.
I perhaps should mention that most objects will not be able to be serialized since they likely use pointers to some degree. Such is the case with std::string, and you have to write the data and not their buffer pointers to a binary file.
With the smallest changes possible, this certainly works:
Code:
#include <fstream>
#include <iostream>
#include <vector>
class Data
{
int x;
char y;
public:
Data()
{
//nothin
}
Data( int my_x, char my_y ):x(my_x), y(my_y)
{
//nothin
}
void display (std::ostream &out) const
{
out << x << " : " << y << '\n';
}
};
int main()
{
Data one(1, '1');
Data two(2, '2');
Data three(3, '3');
std::vector<Data> elems;
elems.push_back(one);
elems.push_back(two);
elems.push_back(three);
elems.push_back(one);
elems.push_back(two);
elems.push_back(three);
std::fstream example;
example.open("stuff.bin", std::ios_base::out | std::ios_base::binary);
if( example.is_open() ) {
for( std::vector<Data>::iterator it = elems.begin(); it != elems.end(); it++ ) {
example.write((char*)&*it, sizeof *it);
}
example.close();
}
example.open("stuff.bin", std::ios_base::in | std::ios_base::binary);
if( example.is_open() ) {
Data d;
while( example.read((char*)&d, sizeof d) ) {
d.display(std::cout);
}
example.close();
}
return 0;
}