二进制文件之写文件
打开方式要指定为:ios::binary
二进制方式写文件主要利用流对象调用函数write
函数原型:ostream& write(const char buffer,int len);
参数解释:内存指针buffer指向内存中一段存储空间,len是读写的字数
二进制文件写文件步骤:
1.包含头文件:#include< fstream >
2.创建流对象:ofstream ofs
3.打开文件:ofs.open(“person.txt”,ios::out | ios::binary);
4.写文件: ofs.write(const char * buffer,int len);
5.关闭文件:ofs.close()
#include<iostream>
using namespace std;
#include<fstream>
class person {
public:
char name[64];
int age;
};
int main()
{
ofstream ofs;
ofs.open("person.txt", ios::out | ios::binary);
/*char ch[64] = "大忽悠";
ofs.write((const char*)ch, sizeof(ch));*/
person p = { "大忽悠",19 };
ofs.write((const char*)&p, sizeof(p)); //要进行强制类型转换,传入的是指针,填入的是一个地址
ofs.close();
system("pause");
return 0;
}