文件操作:二进制文件(写/读)

以二进制的方式对文件进行读写操作其打开方式要指定为 ios::binary

二进制方式写文件主要利用流对象调用成员函数write

函数原型 : ostream& write(const char * buffer,int len);

参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数

cpp 复制代码
#include<iostream>
using namespace std;
#include<fstream>

//二进制文件 写文件
class Person
{
public:

	char m_Name[64];//姓名    写字符串用C的字符数组代表一个字符串
	int m_Age;//年龄
};

void test()
{
	//1.包含头文件

	//2.创建流对象
	ofstream ofs("person.txt", ios::out | ios::binary);

	//3.打开文件
	//ofs.open("person.txt", ios::out | ios::binary);两种方式
	
	//4.写文件
	Person p = { "张三",18 };
	ofs.write((const char*)&p, sizeof(Person));

	//5.关闭文件
	ofs.close();
}

int main()
{
	test();

	return 0;
}

二进制方式读文件主要利用流对象调用成员函数read

函数原型: istream& read(char *buffer,int len);

参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数

cpp 复制代码
#include<iostream>
using namespace std;
#include<fstream>

//二进制文件 读文件
class Person
{
public:
	char m_Name[64];//姓名
	int m_Age;//年龄

};

//二进制文件 读文件
void test()
{
	//1.包含头文件

	//2.创建流对象
	ifstream ifs;

	//3.打开文件 判断文件是否打开成功
	ifs.open("person.txt", ios::in | ios::binary);

	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
        return;
	}

	//4.读文件
	Person p;
	ifs.read((char*)&p, sizeof(Person));
	cout << "姓名:" << p.m_Name << " 年龄:" << p.m_Age << endl;

	//5.关闭文件
	ifs.close();
}

int main()
{

	test();
	return 0;
}
相关推荐
端平入洛1 天前
delete又未完全delete
c++
端平入洛2 天前
auto有时不auto
c++
郑州光合科技余经理3 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1233 天前
matlab画图工具
开发语言·matlab
dustcell.3 天前
haproxy七层代理
java·开发语言·前端
norlan_jame3 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20213 天前
信号量和信号
linux·c++
多恩Stone3 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054963 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月3 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js