你的class里面成员也有class,所以直接用write函数可能会出问题,对于这种情况可以使用MFC提供的“序列化”的功能,把一个class写入二进制文件
如果class里面的成员全是基本数据类型,用write函数写入文件不会出问题。
你的我也不看了,给你个简单的例子,自己琢磨吧!
#include
#include
using namespace std;
struct student
{
int ID;
int age;
};
void main()
{
student st;
st.ID = 0;
st. age = 18;
ofstream ofs("1.data", ios::binary | ios::out);
ofs.write((char*)&st, sizeof(st));
ifstream ifs("1.data", ios::binary | ios::in);
ifs.read((char*)&st, sizeof(st));
cout<
注意不要用 fstream
用ifstream(输入流) 和 ofstream(输出流)
fstream很容易出错
对二进制的读写主要用iostream类成员函数read和write莱实现。这两个成员函数的原型为:
istream&read(char*buffer,int len);
ostream&write(const char* buffer,int len);
字符指针buffer指向内存一段存储空间。len是读写的字节数。
用write写就用read读嘛。。