第二十二课:文件操作
学习目标:
- 理解文件流的概念。
- 学习如何使用C++中的文件操作来读写数据。
- 掌握使用
fstream
,ifstream
, 和ofstream
类进行文件操作。 - 了解文件操作的常见用途。
学习内容:
-
文件流的概念:
文件流是一种数据流,它从文件中读取数据或向文件中写入数据。在C++中,你可以通过包含头文件<fstream>
来使用文件流。 -
打开和关闭文件:
在C++中,可以使用ofstream
(输出文件流)创建文件并向文件写入数据,使用ifstream
(输入文件流)从文件读取数据,以及使用fstream
(文件流)来同时进行读写操作。代码示例:
#include <iostream> #include <fstream> using namespace std; int main() { // 写入文件 ofstream outfile("example.txt"); outfile << "This is an example text." << endl; outfile.close(); // 关闭文件流 // 读取文件 ifstream infile("example.txt"); string line; if (infile.is_open()) { while (getline(infile, line)) { cout << line << '\n'; } infile.close(); // 关闭文件流 } else { cout << "Unable to open file"; } return 0; }
预计输出效果:
This is an example text.
-
检查文件是否成功打开:
使用is_open()
方法可以检查文件是否成功打开。 -
文件操作的使用场景:
文件操作通常用于数据持久化,例如保存程序的配置信息,存储用户生成的数据,或读取外部数据文件等。
练习题:
编写一个程序,它首先要求用户输入他们的名字和年龄。然后程序将这些信息保存到一个名为 “userinfo.txt” 的文件中。最后,程序读取这个文件,并将内容打印到控制台。
答案:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string name;
int age;
// 获取用户输入
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter your age: ";
cin >> age;
// 写入文件
ofstream outfile("userinfo.txt");
if (outfile.is_open()) {
outfile << "Name: " << name << endl;
outfile << "Age: " << age << endl;
outfile.close();
cout << "Information saved." << endl;
} else {
cout << "Unable to open file for writing." << endl;
}
// 读取文件
ifstream infile("userinfo.txt");
string line;
if (infile.is_open()) {
while (getline(infile, line)) {
cout << line << '\n';
}
infile.close();
} else {
cout << "Unable to open file for reading." << endl;
}
return 0;
}
预计输出效果(示例):
Enter your name: John Doe
Enter your age: 30
Information saved.
Name: John Doe
Age: 30
在这个练习中,学生将学会如何获取用户输入,将数据写入文件,并从文件中读取数据。这些技能是文件处理和数据持久化的基础,并且是编程中常见的操作。