用二进制方式操作文件,需要指定方式 ios::binary
二进制方式写文件主要利用流对象调用成员函数write
函数原型:
ostream & write (const char * buffer,int len)
参数:buffer是字符指针,指向内存中一段储存空间,len是读写的字节数
#include<iostream>
#include<string>
#include<fstream>//包含头文件
using namespace std;
class A
{
public:
char a[10];
int b;
};
void t1()
{
//创建输出流对象
ofstream ofs;
ofs.open("t2.txt", ios::out | ios::binary);
//或把上两行换成ofstream ofs("t1.txt", ios::out | ios::binary);
//因为ofs这个对象里有构造函数
A p = { "abcd",10 };
//写文件
ofs.write((const char*)&p, sizeof(A));
//关闭文件
ofs.close();
}
int main()
{
t1();
system("pause");
return 0;
}