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)); } 性能優化