1.写文件
二进制方式写文件,利用流对象的成员函数write。
函数原型: ostream & write(const char * buffer, int len);
参数含义:buffer指向内存中一段存储空间,len是写的字节数。
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Person
{
public:
char mName[64];
int mAge;
};
int main()
{
Person person = { "April", 23 };
ofstream ofs;
ofs.open("person.txt", ios::out | ios::binary);
ofs.write((const char *)&person, sizeof(person));
ofs.close();
getchar();
return 0;
}
2.读文件
二进制方式读文件,利用流对象的成员函数read。
函数原型: istream & read(char *buffer, int len);
参数含义:buffer指向内存中一段存储空间,len是读的字节数。
#include<iostream>
#include<fstream>
using namespace std;
class Person
{
public:
char mName[64];
int mAge;
};
int main()
{
ifstream ifs;
ifs.open("person.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "read fail." << endl;
return -1;
}
Person person;
ifs.read((char *)&person, sizeof(person));
ifs.close();
getchar();
return 0;
}