---文件操作---

复制代码
#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();
}
相关推荐
木兰不吃草1 小时前
mac playCover 金铲铲无法使用麦克风问题详细教程
macos·语音·麦克风·playcover·金铲铲
伟大的大威2 小时前
【零基础入门】Open-AutoGLM 完全指南:Mac 本地部署 AI 手机助理(原理+部署+优化)附上修改后代码
macos
xing-xing2 小时前
Java多版本配置及版本切换(Mac适配)
java·macos
_Johnny_3 小时前
解决Mac安装软件提示`已损坏无法打开`,`请移到废纸篓`
macos
雪域迷影3 小时前
macOS中使用cJSON解析库解析JSON
c++·macos·json·c·cmake·pkg-config
qq_2515335913 小时前
使用 Python 提取 MAC 地址
网络·python·macos
linweidong18 小时前
网易ios面试题及参考答案(下)
objective-c·swift·ios开发·切面编程·ios面试·苹果开发·mac开发
24zhgjx-fuhao1 天前
配置MAC地址安全
macos
Wcowin1 天前
OneClip 开发经验分享:从零到一的 macOS 应用开发
经验分享·macos·策略模式
询问QQ:276998851 天前
工业物联网,车间物联网,车间可视化看板。 从PLC到组态软件,到大屏数据可视化。 1、支持车间...
objective-c