---文件操作---

复制代码
#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();
}
相关推荐
上去我就QWER10 小时前
macOS下如何全文检索epub格式文件?
macos
库奇噜啦呼10 小时前
【iOS】音频与视频播放
ios·音视频·cocoa
谢娘蓝桥11 小时前
Mac 安装 Xcode 及qt 环境安装
ide·macos·xcode
witton14 小时前
克隆整个macOS系统到新磁盘
macos·asr·克隆·复制·迁移·恢复·restore
csdn_aspnet16 小时前
如何在 Mac、Ubuntu、CentOS、Windows 上安装 MySQL 客户端
linux·windows·mysql·macos·centos
我的golang之路果然有问题16 小时前
mac M系列芯片 unity 安装会遇到的错误以及解决
经验分享·学习·macos·unity·游戏引擎
心灵宝贝18 小时前
如何安装 PDF Reader Pro for Mac v3.2.1.0?超简单DMG安装步骤(附安装包)
macos
by__csdn1 天前
nvm命令使用,nvm国内镜像,nvm命令for Linux/Mac
linux·运维·macos
伟大的大威1 天前
Android 端离线语音控制设备管理系统:完整技术方案与实践
android·macos·xcode
Yooooung_Lee1 天前
七家咨询公司的PPT标准配色模版(macos+Office LTSC Standard for Mac 2024)
macos·powerpoint