01 文本文件-写文件

02 文本文件-读文件

03 二进制文件-写文件

04 二进制文件-读文件

01 文本文件-写文件

#include<iostream>
using namespace std;
//1,写入头文件
#include<fstream>

void test1()
{
	// 2.创建流对象
	ofstream file;
	//3.指定打开方式
	file.open("test.txt", ios::out);
	//4.写入文件
	file << "张三" << endl;
	file << "19岁" << endl;

	//5.关闭文件
	file.close();
}
int main()
{
	test1();
	system("pause");
	return 0;
}

//总结:
//●文件操作必须包含头文件fstream
//●读文件可以利用ofstream ,或者fstream类
//●打开文件时候需要指定操作文件的路径,以及打开方式
//●利用 << 可以向文件中写数据
//●操作完毕,要关闭文件

02 文本文件-读文件

#include<iostream>
using namespace std;
//1,写入头文件
#include<fstream>
#include<string>
void test1()
{
	// 2.创建流对象
	ifstream file;
	//3.指定打开方式
	file.open("test.txt", ios::in);
	while (! file.is_open())
	{
		cout << "文件打开失败" << endl;
		return ;
	}
	//4.读取
	//①第一种读取
	//char buf[1024] = { 0 };
	//while (file >>buf)
	//{
		//cout << buf << endl;

	//}
	//②第二种读取(推荐)
	char buf[1024] = {0};
	while (file.getline(buf, sizeof(buf)))
	{
		cout << buf << endl;

	}
	//③第三种读取
	//string buf;
	//while ( getline(file, buf))	//保护string头文件才不会报错
	//{
	//	cout << buf << endl;

	//}
	//④第四种读取(不推荐,一个字一个字读效率低)
	//char c;
	//while ((c = file.get()) != EOF) //EOF end of file
	//{
	//	cout << c;
	//}

	//5.文件关闭
	file.close();
}
int main()
{
	test1();
	system("pause");
	return 0;
}

03 二进制文件-写文件

#include<iostream>
using namespace std;
//1.写入头文件
#include <fstream>

class Person
{
public:
	char name[64];
	int age;
};

void test1()
{
	//2.创建流对象
	ofstream file("Person.txt", ios::out | ios::binary);
	//3.打开文件
	//file.open("Person.txt", ios::out | ios::binary);
	//4.写入文件
	Person p = {"张三", 19};
	file.write((const char *) &p, sizeof(Person));
	//5.文件关闭
	file.close();
}

int main()
{
	test1();
	system("pause");
	return 0;
}
//总结
//文件输出流对象,可以通过writer函数,以二进制方式写数据

04 二进制文件-读文件

#include<iostream>
using namespace std;
//1.写入头文件
#include <fstream>

class Person
{
public:
	char name[64];
	int age;
};

void test1()
{
	//2.创建流对象
	ifstream file("Person.txt", ios::in | ios::binary);
	//3.打开文件
	//file.open("Person.txt", ios::in | ios::binary);
	if (!file.is_open())
	{
		cout << "没有找到文件" << endl;
		return;
	}
	//4.读文件
	
	Person p ;
	file.read((char*)&p, sizeof(Person));
	cout << "姓名:" << p.name << ",年龄:" << p.age << endl;
	//5.文件关闭
	file.close();
}

int main()
{
	test1();
	system("pause");
	return 0;
}
//总结
//文件输出流对象,可以通过read函数,以二进制方式写数据