我有一個結構與2個整數,我想將它們存儲在一個二進制文件,並再次閱讀。C++如何將整數存儲到二進制文件?
這裏是我的代碼:
static const char *ADMIN_FILE = "admin.bin";
struct pw {
int a;
int b;
};
void main(){
pw* p = new pw();
pw* q = new pw();
std::ofstream fout(ADMIN_FILE, ios_base::out | ios_base::binary | ios_base::trunc);
std::ifstream fin(ADMIN_FILE, ios_base::in | ios_base::binary);
p->a=123;
p->b=321;
fout.write((const char*)p, sizeof(pw));
fin.read((char*)q, sizeof(pw));
fin.close();
cout << q->a << endl;
}
我得到的輸出是0
。誰能告訴我有什麼問題?
'fin.write'? 'fin.read',當然。這是真實的代碼嗎?在打開文件輸入前,您可能需要刷新/關閉輸出流。 – 2010-03-24 14:42:40