以二进制方式对文件进行读写操作,打开方式要指定为ios::binary
二进制写文件主要利用流对象调用成员函数 write
函数原型:ostream & write(const char * buffer , int len);
参数解释:字符指针buffer 指向内存中一段存储空间,len是读写的字节数。
具体示例如下:
#include<iostream>
using namespace std;
#include<fstream>
class person
{
public:
char m_name[64];
int m_age;
};
void test01()
{
ofstream ofs;
ofs.open("person",ios::out | ios::binary);
person p = {"joney",18};
ofs.write((const char *) &p,sizeof(person));
ofs.close();
}
int main()
{
test01();
}