---文件操作---

复制代码
#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();
}
相关推荐
大虫小呓14 小时前
本地(macOS)和服务器时间不同步导致的 Bug排查及解决
macos
伊织code16 小时前
pdftk - macOS 上安装使用
macos·pdf·pdftk
马特说2 天前
macOS 搭建 Gitea 私有 Git 服务器教程
git·macos·gitea
ai_xiaogui3 天前
AIStarter:全网唯一跨平台桌面AI管理工具,支持Windows、Mac和Linux一键部署
linux·人工智能·macos·跨平台ai项目一键部署工具·comfyui模型库·高效管理2.19tb模型库·一键配置comfyui模型库
归辞...3 天前
「iOS」————分类与扩展
ios·分类·cocoa
太阳伞下的阿呆3 天前
mac安装node.js
macos·node.js
cyhysr3 天前
redis8.0.3部署于mac
redis·macos
Code季风3 天前
深入理解 Gin 框架的路由机制:从基础使用到核心原理
ide·后端·macos·go·web·xcode·gin
归辞...4 天前
「iOS」————NSOperation
macos·ios·cocoa
后端常规开发人员4 天前
MacOS系统:从Docker Desktop迁移到Colima + 外置硬盘存储
macos·docker·colima·外接硬盘