#文件
文件读写对于打 NOI
赛的同学,一定要会,因为赛事的所有数据,要从比赛提供的文本中读入,最后输出的数据要写到文件里。
文件
文件是存储在某种长期储存设备或临时存储设备中的一段数据流,数据流采用二进制存储,并且归属于计算机文件系统管理之下。
文件主要分为磁盘文件和设备文件。
磁盘文件
文件通常存储在外部介质(如磁盘)上,我们也称之为磁盘文件,它在使用时才调入内存。
从用户或者操作系统使用的角度(逻辑上)把磁盘文件分为两类:文本文件和二进制文件。
设备文件
在操作系统中把每一个与主机相连的输入、输出设备看作是一个文件,把它们的输入、输出等同于对磁盘文件的读和写。
stdin(标准输入文件)
stdout(标准输出文件)
stderr(标准错误文件)
当程序启动时,系统默认打开这三个文件
#C语言文件读写
基于C语言的文件读写
头文件:
#include <stdio.h>
打开文件函数:
返回类型
FILE* freopen(const char* path, const char* mode, FILE* stream);
path: 文件路径
mode: 文件访问权限,“r” -只读,“w” -只写
stream: 设备文件,stdin标准输入文件、stdout标准输出设备
关闭文件函数:
int fclose(FILE* stream);
C语言的文件读写例子:
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int main() {
// 基于C语言的文件读写
FILE* file_r = freopen("read.txt"/*路径+文件名*/,"r",stdin);
FILE* file_w = freopen("write.txt"/*路径+文件名*/,"w",stdout);
string s1, s2;
cin >> s1 >> s2; // 输入默认从 file_r 获取数据
cout << s1 + " " + s2 << endl; // 输出默认写入 file_w 文件中
// 关闭文件指针
fclose(file_r)
fclose(file_w)
return 0;
}
运行后会读取read.txt文件中的内容,写入到write.txt中
#C++文件读写
基于C++的文件读写
头文件和命名空间
#include <fstream>
处理文件的头文件 文件流
using namespace std
引用该命名空间,不引用将必须使用std::fstring
的方式使用该类
::
两个冒号叫作用域
打开文件:
ifstream srcFile("in.txt", ios::in); // 以文本模式打开in.txt备读 两个冒号叫作用域
ofstream destFile("out.txt", ios::out); // 以文本模式打开out.txt备写
关闭文件:
destFile.close();
srcFile.close()
C++文件读写例子
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream srcFile("read.txt", ios::in);
ofstream dstFile("write.txt", ios::out);
string s1, s2;
srcFile >> s1 >> s2;
dstFile << s1 + "~" + s2 << endl;
srcFile.close();
dstFile.close();
return 0;
}
#文件读写的应用
文件读写的应用
读取学生成绩单源文件-SchoolReportln.txt中的信息,根据该文件的信息对学生按总成绩进行降序排序,将排序好的成绩单信息存入到学生成绩单目标文件-SchoolReportOut.txt中。
代码实现:
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
struct stu{
int id;
string name;
int tot;
};
int n;
stu a[110]; // 开一个结构体数组
bool cmp(stu A, stu B){
return A.tot > B.tot;
}
int main() {
ifstream srcFile("SchoolReportln.txt", ios::in);
ofstream dstFile("SchoolReportOut.txt", ios::out);
srcFile >> n;
for(int i = 1; i <= n; i++){
srcFile >> a[i].id >> a[i].name >> a[i].tot;
}
sort(a + 1, a + n + 1, cmp);
for(int i = 1; i <= n; i++){
dstFile << a[i].id << " " << a[i].name << " " << a[i].tot << endl;
}
srcFile.close();
dstFile.close();
return 0;
}
运行结果:排序成功 并 将结果写入 SchoolReportOut.txt 文件。