One of the things I noticed in your first program was:
Code:
os.write((char*)&Points, sizeof(Points));
This is incorrect, on my machine sizeof(Points) evaluates to 12 which is not actually the correct size for your class. You should probably be using sizeof(vec3d) for one element, this evaluates to 28 on my machine. So to write the whole vector you would need to write (sizeof(vec3d) * Points.size()) bytes.
However when I tried to write out the entire vector and then read in the entire vector I got the same error you received. When I wrote each element of the vector separately and the read each element separately it worked.
Code:
// Serializing a vector -
// Why I shouldn't read Reddit while watching youtube CompSci videos
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct vec3d
{
vec3d() : x(0.0), y(0.0), z(0.0) {};
vec3d(double xa, double ya, double za) : x(xa), y(ya), z(za) {}
virtual ~vec3d() {}
double x;
double y;
double z;
};
typedef vector<vec3d> PointList;
int main()
{
cout << "Structure" << endl;
cout << "---------" << endl;
PointList Points;
vec3d P1(1.99, 5.0, 9.0); Points.push_back(P1);
vec3d P2(2.0, 6.0, 10.555); Points.push_back(P2);
vec3d P3(3.0, 7.55, 11.0); Points.push_back(P3);
vec3d P4(4.5, 8.0, 12.0); Points.push_back(P4);
// Searializing struct to point.dat
ofstream os("points.dat", ios::binary);
if(!os.is_open()) {
cout << "Error opening points.dat for write" << endl;
return 1;
}
for(size_t i = 0; i < Points.size(); ++i)
{
os.write((char*)&Points[i], sizeof(vec3d));
}
os.close();
PointList NewPoints;
int file_sz;
// Reading from it
ifstream is("points.dat", ios::binary);
if(!is.is_open()) {
cout << "Error opening points.dat for read" << endl;
return 1;
}
is.seekg(0, ios::end);
file_sz = is.tellg();
is.seekg(0, ios::beg);
NewPoints.resize(file_sz/sizeof(vec3d));
for(size_t i = 0; i < NewPoints.size();++i)
is.read((char*)&NewPoints[i], sizeof(vec3d));
// Display
cout << "Output:" << endl;
PointList::const_iterator it;
for(it = NewPoints.begin(); it != NewPoints.end(); ++it)
{
cout << it->x << " " << it->y << " " << it->z << endl;
}
return 0;
}
Jim