本专栏记录C++学习过程包括C++基础以及数据结构和算法,其中第一部分计划时间一个月,主要跟着黑马视频教程,学习路线如下,不定时更新,欢迎关注。
当前章节处于:
---------第1阶段-C++基础入门
---------第2阶段实战-通讯录管理系统,
=====>第3阶段-C++核心编程,
---------第4阶段实战-基于多态的企业职工系统
---------第5阶段-C++提高编程
---------第6阶段实战-基于STL泛化编程的演讲比赛
---------第7阶段-C++实战项目机房预约管理系统
文章目录
- 1. 概述
 - 2. 写文件
 - 3. 读文件
 - 3. 二进制写文件
 - 4. 以二进制形式读文件
 
1. 概述
程序运行时产生的数据都属于临时数据,程序一旦运行结束都会被释放,通过文件的方式可以将数据持久化,C++中对文件操作需要包含头文件<fstream>
 文件类型分为两种:
- 文本文件 - 文件以文本的ASCII码形式存储在计算集中
 - 二进制文件 - 文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂他们
 
操作文件的三大类:
- ofstream:写操作
 - ifstream:读操作
 - fstrean:读写操作
 
2. 写文件
写文件的步骤:
- 包含头文件 # include <fstream>
 - 创建流对象 ofstream ofs;
 - 打开文件 ofs.open(“文件路径”,打开方式)
 - 写数据 ofs<<“写入的数据”;
 - 关闭文件 ofs.close()
 

 打开方式可以配合使用,用 | 操作符
#include <iostream>
using namespace std;
# include <fstream>;
int main() {
	fstream ofs;
	ofs.open("test.txt", ios::out);  // 如果不存在会先创建
	ofs << "Hello World!" << endl;
	ofs.close();
	system("pause");
	return 0;
}
 
test.txt
Hello World!
 
3. 读文件
读文件与写文件步骤相似,但是读取方式相对比较多
 步骤如下:
- 包含头文件 # include <fstream>
 - 创建流对象 ifstream ifs;
 - 打开文件并判断文件是否打开成功 ifs.open(“文件路径”,打开方式);
 - 读数据 四种方式读取
 - 关闭文件 ifs.close();
 
#include <iostream>
# include <fstream>
using namespace std;
# include <string>
int main() {
	ifstream ifs;
	ifs.open("test.txt", ios::in);
	// 读文件 方法一
	//char buf[1024] = { 0 };
	//while (ifs >> buf) {
	//	cout << buf << endl;
	//}
	// 方法二
	//char buf[1024] = { 0 };
	//while (ifs.getline(buf,1024)) {
	//	cout << buf << endl;
	//}
	// 方法三 
	//string buf;
	//while (getline(ifs,buf)) {
	//	cout << buf << endl;
	//}
	char c;
	while ((c=ifs.get())!=EOF) {
		cout << c;
	}
	system("pause");
	return 0;
}
 
Hello World!
张三
李四
12345请按任意键继续. . .
 
3. 二进制写文件
#include <iostream>
using namespace std;
#include <fstream>
class Person {
public:
	char name[64];
	int age;
};
int main() {
	ofstream ofs;
	ofs.open("Person.txt",ios::out|ios::binary);
	Person p = {"张三",17};
	// 以二进制形式写文件
	ofs.write((const char*)&p, sizeof(p));
	ofs.close();
	cout << "写入完成!" << endl;
	system("pause");
	return 0;
}
 
写入完成!
请按任意键继续. . .
 
4. 以二进制形式读文件
#include <iostream>
using namespace std;
#include <fstream>
class Person {
public:
	char name[64];
	int age;
};
int main() {
	ifstream ifs;
	ifs.open("Person.txt", ios::out | ios::binary);
	// 以二进制形式写文件
	Person p;
	ifs.read((char*)&p, sizeof(p));
	cout << "读入完成!" << endl;
	cout << "姓名:" << p.name <<"   年龄:" << p.age <<endl;
	ifs.close();
	system("pause");
	return 0;
}
 
读入完成!
姓名:张三   年龄:17
请按任意键继续. . .
                


















