Before someone hits me with a "Use Boost" - know that I want to know how to do this myself.And I've had a few beers. Here it is:
So, I seem to get the data I want, but then there's what looks like a seg fault. Big old Glibc error.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() {}; vec3d(double x, double y, double z) {this->x = x; this->y = y; this->z = z;} 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; } //int magicnumber = sizeof(Points); os.write((char*)&Points, sizeof(Points)); 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); //is.read((char*)&NewPoints, magicnumber); NewPoints.resize(file_sz); is.read((char*)&NewPoints, file_sz); // 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; }Sounds like a cool error.Code:*** glibc detected *** /storage/Projects/Recent/File Input and Output/bin/Debug/File Input and Output: corrupted double-linked list: 0x0000000000866110 ***
Now, I would think the size of the file would suffice as the size of the NewPoints vector. But there's padding and other stuff going on, I'm sure. If someone has time, show mercy - waxing educational is welcome.
Writing and reading a vector to a binary file should not be that hard, and it probably isn't - but c++ is an expert's language... and I'm not there yet.
Side note: I picked up Scott Meyers Effective C++, I love it. Very approachable style, not nearly as dry as Koenig & Moo.
Edit: I know that's a c-style ungreppable cast, and I hate it too. But the C++ static_cast wouldn't even compile. I'm so ashamed, so very
ashamed.
Edit 2: Reading Salem's recommended link
[36] Serialization and Unserialization ..Updated!.., C++ FAQnow... =)



LinkBack URL
About LinkBacks
And I've had a few beers. Here it is:



I used to be an adventurer like you... then I took an arrow to the knee.