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() {// Create and open a text fileofstream MyFile("filename.txt");// Write to the fileMyFile << "Files can be tricky, but it is fun enough!";// Close the fileMyFile.close();}
我们为什么要关闭文件?
这被认为是良好的习惯,它可以清理不必要的内存空间。读取文件
要读取文件,请使用 ifstream 或 fstream 类以及文件名。
注意,我们还使用 while 循环和 getline() 函数(属于 ifstream 类)逐行读取文件,并打印文件内容:
实例
#include <iostream>#include <fstream>#include <string>using namespace std;int main () {// Create a text fileofstream MyWriteFile("filename.txt");// Write to the fileMyWriteFile << "Files can be tricky, but it is fun enough!";// Close the fileMyWriteFile.close();// Create a text string, which is used to output the text filestring myText;// Read from the text fileifstream MyReadFile("filename.txt");// Use a while loop together with the getline() function to read the file line by linewhile (getline (MyReadFile, myText)) {// Output the text from the filecout << myText;}// Close the fileMyReadFile.close();}