二进制文件数据的读取和写入出错
/***********************************二进制文件数据的读取和写入
***********************************/
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int age,height,readAge,readHeight;
cout<<"please input age and height:";
cin>>age>>height;
ofstream outBinaryFile("binary.abc",ios::binary|ios::app);
if(outBinaryFile.fail())
{
cout<<"open file failed."<<endl;
exit(0);
}
outBinaryFile.write(reinterpret_cast<char *>(&age),sizeof(age));
outBinaryFile.write(reinterpret_cast<char *>(&height),sizeof(height));
outBinaryFile.close();
ifstream inBinaryFile("binary.abc",ios::binary);
if(inBinaryFile.fail())
{
cout<<"open file failed."<<endl;
exit(0);
}
inBinaryFile.seekg(-sizeof(int)*2,ios::end); //每次读文件,从文件末尾前移两个int字节,不知道对不对,请各位指点
inBinaryFile.read(reinterpret_cast<char *>(&readAge),sizeof(readAge));
inBinaryFile.read(reinterpret_cast<char *>(&readHeight),sizeof(readHeight));
inBinaryFile.close();
cout<<"age from file:"<<readAge<<endl
<<"height from file:"<<readHeight<<endl;
return 0;
}
输出的数值不对