大家好:
衷心希望各位点赞。
您的问题请留在评论区,我会及时回答。
二进制文件操作
以二进制的方式对文件进行读写操作。
打开方式要指定为 ios::binary
写文件
二进制方式写文件主要利用流对象调用成员函数 write
wirte函数的参数意义:
字符指针buffer:指向内存空间中一段存储空间
len:是读写的字节数。
#include <iostream>
#include <Windows.h>
#include <string>
#include <fstream> // 头文件包含
using namespace std;
class Person
{
public:
char m_Name[64];
int m_Age;
};
int main(void)
{
ofstream ofs;
ofs.open("person.txt", ios::binary | ios::out);
// 准备数据
Person p = { "张三", 18 };
// 写文件
ofs.write((const char*)&p, sizeof(Person));
ofs.close();
system("pause");
return 0;
}
读文件
二进制方式读文件主要利用流对象调用成员函数 read
参数解释:
buffer:字符指针指向内存中一段存储空间。
len:是读写的字节数。
#include <iostream>
#include <Windows.h>
#include <string>
#include <fstream> // 头文件包含
using namespace std;
class Person
{
public:
char m_Name[64];
int m_Age;
};
int main(void)
{
// 包含头尾文件
// 创建流对象
ifstream ifs;
// 打开文件,并判断文件是否打开
ifs.open("person.txt", ios::binary | ios::in);
if (!ifs.is_open())
{
cout << "打开文件失败" << endl;
return 0;
}
// 读文件
// 事先准备Person类型变量接收数据
Person p;
ifs.read((char*) &p, sizeof(Person));
cout << "姓名:" << p.m_Name << " 年龄:" << p.m_Age << endl;
// 关闭文件
ifs.close();
system("pause");
return 0;
}
运行截图:
总结
记住read函数的使用方法:事先准备变量接收数据。
文件输入流对象调用成员函数read,以二进制方式读数据。