C++核心高级编程 --- 5.文件操作

发布于:2024-04-04 ⋅ 阅读:(138) ⋅ 点赞:(0)

第五章:

5.文件操作

作用:程序运行时产生的数据都是临时数据,程序运行结束后都会被释放,文件能将数据持久化

对文件进行操作需要包含头文件

两种文件类型

  • 文本文件:以文本ASCII码形式存储在计算机里

  • 二进制文件:以文本二进制形式存储在计算机里

操作文件的三大类:

  • ofstream 写操作

  • ifstream 读操作

  • fstream 读写操作

5.1 文本文件
5.1.1 写文件

步骤

  1. 包含头文件:#include

  2. 创建流对象:ofstream ofs;

  3. 打开文件:ofs.open(“文件路径”, 打开方式);

  4. 写入数据:ofs << “写入的数据”

  5. 关闭文件:ofs.close();

文件打开方式:

打开方式 说明
ios::in 为读文件而打开文件
ios::out 为写文件而打开文件
ios:ate 初始位置为文件尾
ios::app 追加方式写文件
ios::trunc 如果文件存在会先删除,再创建
ios::binary 二进制方式打开文件

文件打开方式可配合使用,用|操作符即可。

如用二进制方式写文件:ios::binary | ios::out

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	ofstream ofs;
	ofs.open("text.txt", ios::out);
	ofs << "hello world" << endl;
	ofs << "hello C++" << endl;
	ofs.close();
	system("pause");
	return 0;
}
5.1.2 读文件

步骤

  1. 包含头文件:#include

  2. 创建流对象:ifstream ifs;

  3. 打开文件并判断打开是否成功:ifs.open(“文件路径”,打开方式)

  4. 读取数据:四种方式,代码中会说明

  5. 关闭文件:ifs.close();

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	ifstream ifs;
	ifs.open("text.txt", ios::in);
	if (!ifs.is_open())  //判断文件是否打开成功
	{
		cout << "打开文件失败!" << endl;
		return 0;
	}

	//读取数据
	//第一种方式
	/*char buf[1024] = { 0 };
	while (ifs >> buf)
	{
		cout << buf << endl;
	}
	system("pause");*/
	
	//第二种方式
	/*char buf[1024] = { 0 };
	while (ifs.getline(buf, sizeof(buf)))
	{
		cout << buf << endl;
	}*/

	//第三种方式
	/*string buf;
	while (getline(ifs, buf))
	{
		cout << buf << endl;
	}*/


	//第四种方式
	char c;
	while ((c = ifs.get()) != EOF)
	{
		cout << c;
	}

	ifs.close();
	return 0;
}
5.2 二进制文件

打开方式指定:ios::binary

5.2.1 写文件

二进制方式写文件可用流对象调用成员函数write

函数原型:ostream& write(const char * buffer, int len);

说明:字符指针buffer指向内存中一段存储空间。len是读写的字节数。

#include <iostream>
#include <fstream>
using namespace std;

class Student
{
public:
	char name[20];
	int age;
};

int main()
{
	ofstream ofs("stuInfo.txt", ios::out | ios::binary);
	Student s = { "小明", 18 };
	ofs.write((const char*)&s, sizeof(Student));
	ofs.close();
	system("pause");
	return 0;
}
5.2.2 读文件

二进制方式读文件可用流对象调用成员函数read

函数原型:istream& read( char * buffer, int len);

说明:字符指针buffer指向内存中一段存储空间。len是读写的字节数。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Student
{
public:
	char name[20] ;
	int age;
};

int main()
{
	ifstream ifs;
	ifs.open("stuInfo.txt", ios::binary | ios::in);
	if (!ifs.is_open())
	{
		cout << "打开文件失败!" << endl;
		return 0;
	}
	Student s;
	ifs.read((char*)&s, sizeof(s));
	cout << "姓名:" << s.name << " 年龄:" << s.age << endl;
	ifs.close();
	system("system");
	return 0;
f(s));
	cout << "姓名:" << s.name << " 年龄:" << s.age << endl;
	ifs.close();
	system("system");
	return 0;
}

网站公告

今日签到

点亮在社区的每一天
去签到