---文件操作---

复制代码
#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();
}
相关推荐
钟念17 小时前
【打包app】uniapp打包ios端和安卓端app
macos·objective-c·cocoa
森之鸟1 天前
Mac电脑上如何打印出字体图标
前端·javascript·macos
m_136871 天前
Mac M 系列芯片 YOLOv8 部署教程(CPU/Metal 后端一键安装)
yolo·macos
搜狐技术产品小编20232 天前
CAEmitterLayer:iOS 中创建炫酷粒子效果的魔法工具
macos·ios·objective-c·cocoa
未来之窗软件服务2 天前
操作系统应用开发(七)mac苹果模拟器——东方仙盟练气期
macos·仙盟创梦ide·东方仙盟·系统模拟器
liliangcsdn2 天前
Mac本地docker安装Kibana+ElasticSearch
elasticsearch·macos·docker
千寻简2 天前
远程连接Mac操作ClaudeCode一直提示登录Invalid API key · Please run /login
macos
小朋友,你是否有很多问号?2 天前
Mac安装hadoop
hadoop·macos
00后程序员张3 天前
iOS App 混淆与资源保护:iOS配置文件加密、ipa文件安全、代码与多媒体资源防护全流程指南
android·安全·ios·小程序·uni-app·cocoa·iphone
脚踏实地的大梦想家3 天前
【Docker】P2 Docker环境构建准备:MacOS 与 Linux
linux·macos·docker