hey folks,
are there any examples out there on how to save complex data types to binary files using the new ofBuffer class from 007? i’d usually do this with xml, but the file sizes are getting way too large for my project.
something along these lines: http://courses.cs.vt.edu/~cs2604/fall02/binio.html
it looks like using buffer.set(istream & stream) would be the way to go, but istream is proving to be on the complicated side. from what i understand, istreams require a pointer to a streambuffer, which is an existing file. but there’s no existing file in this case.
thanks++,
jeremy
the easiest way to do binary file IO like the page you link to is to use the new ofFile, not ofBuffer.
notice that:
class ofFile: public fstream{
...
}
so everything you can do with an fstream, you can also do with an ofFile.
you’re going to want to open it in binary mode:
ofFile file;
file.open("output.bin", ofFile::WriteOnly, true);
and from there you can use operator<< or write() to write to it.
here’s an example that uses a mix of both techniques to save an ofMesh point cloud to a binary PLY file:
void exportPlyCloud(string filename, ofMesh& cloud) {
ofFile ply;
if (ply.open(filename, ofFile::WriteOnly, true)) {
// write the header
ply << "ply" << endl;
ply << "format binary_little_endian 1.0" << endl;
ply << "element vertex " << cloud.getVertices().size() << endl;
ply << "property float x" << endl;
ply << "property float y" << endl;
ply << "property float z" << endl;
ply << "end_header" << endl;
// write all the vertices
vector<ofVec3f>& surface = cloud.getVertices();
for(int i = 0; i < surface.size(); i++) {
if (surface[i].z != 0) {
// write the raw data as if it were a stream of bytes
ply.write((char*) &surface[i], sizeof(ofVec3f));
}
}
}
}