---文件操作---

复制代码
#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();
}
相关推荐
TheNextByte11 小时前
如何在没有iTunes的情况下重启/恢复出厂设置iPhone
ios·cocoa·iphone
带娃的IT创业者1 小时前
解密OpenClaw系列04-OpenClaw技术架构
macos·架构·cocoa·agent·ai agent·openclaw
带娃的IT创业者2 小时前
解密OpenClaw_03-OpenClaw核心功能特性
macos·系统架构·objective-c·cocoa·软件工程·智能体开发·openclaw
AI逐月4 小时前
Mac 轻量安装 Docker 完整指南(Docker + Colima + Kubernetes)
macos·docker·kubernetes
binderIPC4 小时前
macos环境下FFmpeg打包成.so文件
macos·ffmpeg·音视频
binderIPC4 小时前
macos的FFmpeg环境搭建
macos·ffmpeg·音视频
王中王程序猿25 小时前
Mac IDA动态调试Android应用so文件
macos
xifangge20255 小时前
[报错] SpringBoot 启动报错:Port 8080 was already in use 完美解决(Windows/Mac/Linux)
java·windows·spring boot·macos·错误解决
雪域迷影1 天前
MacOS下源码安装SDL3并运行hello.c示例程序
c语言·开发语言·macos·sdl3
阿捏利1 天前
详解Mach-O(五)Mach-O LC_SYMTAB
macos·ios·c/c++·mach-o