One obvious caveat - string fields must have fixed lengths(e.g. char name[80]). Written in NetBeans, compiled and tested with MinGW.
#include <string>
#include <fstream>
#include <vector>
using namespace std;
template<class C> class FileAccess {
private:
string path;
public:
FileAccess(string p){
path = p;
}
void setPath(string p) {
path = p;
}
bool write(C element) {
fstream f (path.c_str(), ios::out | ios::binary);
if(!f) return false;
f.seekp(0, ios::end);
f.write((char*) &element, sizeof(C));
if(!f.good()) {
f.close();
return false;
}
else {
f.close();
return true;
}
}
C read() {
C buffer;
fstream f(path.c_str(), ios::binary | ios::in);
f.read((char*) &buffer, sizeof(C));
return buffer;
}
bool serialize(vector<C> v) {
int size = v.size();
int i;
fstream f(path.c_str(), ios::out | ios::binary | ios::app);
if(!f) return false;
f.seekg(ios::end);
for(i=0; i<size; i++) {
C record = v[i];
f.write((char*) &record, sizeof(C));
}
if(!f.good()) {
f.close();
return false;
}
else {
f.close();
return true;
}
}
vector<C> unserialize() {
fstream f(path.c_str(), ios::in | ios::binary);
vector<C> ret_vec;
C record;
while(f.read((char*) &record, sizeof(C))) {
ret_vec.push_back(record);
}
f.close();
return ret_vec;
}
~FileAccess() {
}
};












