---文件操作---

#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();
}
相关推荐
ss_dda13 小时前
视频编辑软件Adobe Premiere Pro(Pr)2024WIN/MAC下载及安装教程
macos·adobe·photoshop
Flutter鸿蒙梁典典学院15 小时前
Flutter自动打包ios ipa并且上传
flutter·ios·cocoa
AiFlutter15 小时前
Flutter中添加崩溃分析
macos·objective-c·cocoa
资讯全球17 小时前
让Mac更Mac|明基MA系列显示器上市
macos·计算机外设
柯基的小屁墩18 小时前
mac|安装nginx
nginx·macos
ss_dda19 小时前
专业文字处理与协作软件Adobe InCopy(IC)2024WIN/MAC下载及安装教程
macos·adobe
Xminyang19 小时前
Mac设置文件夹的显示方式:独立窗口显示或者标签页显示
macos·文件夹显示方式
cab519 小时前
如何在Mac中修改pip的镜像源
macos·pip
tekin19 小时前
macos 系统文件操作时提示 Operation not permitted 异常解决方法 , 通过恢复模式 开启 /关闭 SIP方法
macos·mac·sip·恢复模式·csrutil·mac恢复模式进入方法
顶顶年华正版软件官方19 小时前
Mac无法安装软件怎么解决?mac安装软件提示无法验证开发者怎么办
经验分享·macos·电脑·软件需求