C++ 文件
C++ 文件
fstream 库允许我们处理文件。
要使用 fstream 库,需要同时包含标准的 <iostream> 和 <fstream> 头文件:
实例
#include <iostream> #include <fstream>
fstream 库中包含三个类,它们用于创建、写入或读取文件:
| 类 | 描述 |
|---|---|
| ofstream | 创建并写入文件。 |
| ifstream | 从文件中读取。 |
| fstream | ofstream 和 ifstream 的组合:创建、读取和写入文件。 |
创建并写入文件
要创建文件,请使用 ofstream 或 fstream 类,并指定文件名。
要写入文件,请使用插入运算符 (<<)。
实例
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// 创建并打开一个文本文件
ofstream MyFile("filename.txt");
// 写入文件
MyFile << "Files can be tricky, but it is fun enough!";
// 关闭文件
MyFile.close();
}
为什么我们要关闭文件?
这被认为是很好的做法,它可以清理不必要的内存空间。
读取文件
要读取文件,请使用 ifstream 或 fstream 类,以及文件名。
请注意,我们还使用 while 循环与 getline() 函数(属于 ifstream 类)一起逐行读取文件,并打印文件内容:
实例
// 创建一个文本字符串,用于输出文本文件
string myText;
// 从文本文件中读取
ifstream MyReadFile("filename.txt");
// 使用 while 循环和 getline() 函数一起逐行读取文件
while (getline(MyReadFile, myText)) {
// 输出文件中的文本
cout << myText;
}
// 关闭文件
MyReadFile.close();
完整的 <fstream> 参考手册
如需 <fstream> 类和函数的完整参考,请访问我们的 C++ fstream 参考手册。