using namespace std; int main() { int x,y; // mouse coordinates // ..assign values to x and y ofstream archive("coord.dat", ios::binary); archive.write(reinterPRet_cast<char *>(&x), sizeof (x)); archive.write(reinterpret_cast<char *>(&x), sizeof (x)); archive.close(); } 使用reinterpret_cast<>是必要的,因为write()的第一个参数类型为const char*,但&x和&y是int*类型。
以下代码读取刚才存储的值:
#include <fstream>
using namespace std; int main() { int x,y; ifstream archive("coord.dat"); archive.read((reinterpret_cast<char *>(&x), sizeof(x)); archive.read((reinterpret_cast<char *>(&y), sizeof(y)); } 更多内容请看C/C++技术专题 C/C++进阶技术文档 C/C++应用实例专题,或 序列化对象
要序列化一个完整的对象,应把每个数据成员写入文件中:
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::binaryios::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)); } 实现deserialize() 需要一些技巧,因为你需要为字符串分配一个临时缓冲区。做法如下:
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)); } 性能优化