课程进度 75% · 第14/18章第14/18章 · 标签 1/2
— 1 —
文件的打开与关闭
使用文件流进行基本的文件读写操作。
cpp
1
2
3
4
using namespace std;
5
6
int main() {
7
// 写入文件
8
ofstream outFile("example.txt");
9
if (outFile.is_open()) {
10
outFile << "Hello, World!" << endl;
11
outFile << "这是第二行" << endl;
12
outFile.close();
13
} else {
14
cerr << "无法打开文件!" << endl;
15
}
16
17
// 读取文件
18
ifstream inFile("example.txt");
19
if (inFile.is_open()) {
20
string line;
21
while (getline(inFile, line)) {
22
cout << line << endl;
23
}
24
inFile.close();
25
}
26
27
// 文件打开模式
28
ofstream outFile2("binary.dat", ios::binary | ios::out);
29
ifstream inFile2("text.txt", ios::in);
30
31
// 检查文件状态
32
if (inFile2.good()) {
33
cout << "文件状态正常" << endl;
34
}
35
if (inFile2.eof()) {
36
cout << "到达文件末尾" << endl;
37
}
38
if (inFile2.fail()) {
39
cout << "操作失败" << endl;
40
}
41
}
📖ifstream:输入文件流用于读取;ofstream:输出文件流用于写入;fstream:同时支持读写
— 2 —
二进制文件操作
处理二进制文件的读写操作,适用于复杂数据结构。
cpp
1
struct Student {
2
char name[50];
3
int age;
4
double score;
5
};
6
7
int main() {
8
// 写入二进制文件
9
Student s1 = {"张三", 20, 95.5};
10
Student s2 = {"李四", 19, 88.5};
11
12
ofstream outFile("students.dat", ios::binary);
13
if (outFile.is_open()) {
14
outFile.write(reinterpret_cast<char*>(&s1), sizeof(Student));
15
outFile.write(reinterpret_cast<char*>(&s2), sizeof(Student));
16
outFile.close();
17
}
18
19
// 读取二进制文件
20
vector<Student> students;
21
ifstream inFile("students.dat", ios::binary);
22
if (inFile.is_open()) {
23
Student s;
24
while (inFile.read(reinterpret_cast<char*>(&s), sizeof(Student))) {
25
students.push_back(s);
26
}
27
inFile.close();
28
}