| class MP3_clip { private: std::time_t date; std::string name; int bitrate; bool stereo; public: void serialize(); void deserialize(); //.. }; void MP3_clip::serialize() { int size=name.size();// store name's length //empty file if it already exists before writing new data ofstream arc("mp3.dat", ios::binary|ios::trunc); arc.write(reinterpret_cast<char *>(&date),sizeof(date)); arc.write(reinterpret_cast<char *>(&size),sizeof(size)); arc.write(name.c_str(), size+1); // write final '\0' too arc.write(reinterpret_cast<char *>(&bitrate), sizeof(bitrate)); arc.write(reinterpret_cast<char *>(&stereo), sizeof(stereo)); } |
| void MP3_clip::deserialize() { ifstream arce("mp3.dat"); int len=0; char *p=0; arc.read(reinterpret_cast<char *>(&date), sizeof(date)); arc.read(reinterpret_cast<char *>(&len), sizeof(len)); p=new char [len+1]; // allocate temp buffer for name arc.read(p, len+1); // copy name to temp, including '\0' name=p; // copy temp to data member delete[] p; arc.read(reinterpret_cast<char *>(&bitrate), sizeof(bitrate)); arc.read(reinterpret_cast<char *>(&stereo), sizeof(stereo)); } |
| void MP3_clip::serialize() { ofstream arc("mp3.dat", ios::binary|ios::trunc); arc.write(reinterpret_cast<char *>(this),sizeof(*this)); } |