---文件操作---

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

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

	//2.创建流对象

	ofstream ofs;

	//3.指定打开方式
	ofs.open("test.txt", ios::out);//写文件

	//4.写内容
	ofs << "张三" << endl;
	ofs << "喜欢" << endl;
	ofs << "小狗" << endl;

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

int main()
{
	test01();
}
复制代码
#include<iostream>
using namespace std;
#include<fstream>
#include<string>

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

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

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

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

	//4.读数据

	//第一种	存放至数组里边
	//char buf[1024] = { 0 };
	//while (ifs >> buf)
	//{
	//	cout << buf << endl;
	//}

	//第二种
	//调用ifs中的getline函数
	//char buf[1024] = { 0 };
	//while (ifs.getline(buf, sizeof(buf)))
	//{
	//	cout << buf << endl;
	//}

	//第三种  放入字符串中
	string buf;
	while (getline(ifs, buf))
	{
		cout << buf << endl;
	}
	//5.关闭文件
	ifs.close();
}


int main()
{
	test01();
}
复制代码
#include<iostream>
using namespace std;
#include<fstream>

class Person
{
public:
	char m_Name[64];
	int m_Age;
};
void test01()
{
	//1.包含头文件

	//2.创建流对象
	//还有一种直接创建对象和打开文件一块实现 调用了ofs的构造函数
	/*ofstream ofs("penrson.txt",ios::out|ios::binary);*/
	ofstream ofs;
	//3.打开文件
	ofs.open("person.txt", ios::out | ios::binary);

	//4.写文件
	Person p = { "张三",18 };
	ofs.write((const char*)&p, sizeof(Person));

}

int main()
{
	test01();
}

----------------------二进制读文件----------------------------

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

class Person
{
public:
	char m_Name[64];
	int m_Age;
};

void test01()
{
	//1.创建流对象
	ifstream ifs;

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

	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return;
	}
	//3.读文件
	Person p;
	ifs.read((char*)&p, sizeof(Person));
	cout << "姓名: " << p.m_Name << "年龄: " << p.m_Age << endl;

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

int main()
{
	test01();
}
相关推荐
掘根10 小时前
【即时通讯项目】环境搭建9——语言平台
ide·macos·xcode
帅得不敢出门12 小时前
MacOS安装VSCode在QEMU上模拟跑FreeRtos
ide·vscode·macos·freertos·rtos
Sahadev_12 小时前
macOS 解决 AirDrop 传输应用“已损坏“问题,以sublime为例
macos·策略模式·sublime text
pop_xiaoli13 小时前
【iOS】alloc & init & new源码阅读
macos·ios·objective-c·cocoa·xcode
MonkeyKing_sunyuhua1 天前
Mac 上用 MTR 做链路测试很适合排查“ping 不通 / 偶发丢包 / 某一跳延迟高”的问题
macos
FreeBuf_1 天前
苹果紧急发布iOS 15.8.7更新以防御“Coruna“漏洞利用工具包
macos·ios·cocoa
BIBABULALA1 天前
语音算法面试复习系列1——语音信号处理基础(上)
macos·语音识别·xcode
TESmart碲视1 天前
Mac+PC双系统如何共享双屏?KVM切换器选购的5个关键指标|TESmart用户真实体验复盘
macos·计算机外设·kvm切换器·tesmart·双屏kvm切换器·碲视
00后程序员张1 天前
使用克魔助手(Keymob)查看 iOS 设备日志与崩溃报告
android·macos·ios·小程序·uni-app·cocoa·iphone
&黄昏的乐师1 天前
VMware安装MAC虚拟机教程(安装过程记录)
macos