C++ 文件

创建于 2024-12-03 / 28
字体: [默认] [大] [更大]

C++ 文件操作

fstream 库允许我们处理文件。

要使用fstream 库,请同时包含标准 <iostream> <fstream> 头文件:

实例

#include <iostream>
#include <fstream>

fstream 库中包含三个类,用于创建、写入或读取文件:

描述
ofstream 创建和写入文件
ifstream 从文件读取
fstream ofstream和ifstream的组合:创建、读取和写入文件

创建并写入文件

要创建文件,请使用 ofstream or 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 or fstream 类以及文件名。

注意,我们还使用 while 循环和 getline() 函数 (属于 ifstream 类)逐行读取文件,并打印文件内容:

实例

// 创建一个文本字符串,用于输出文本文件
string myText;

// 从文本文件中读取
ifstream MyReadFile("filename.txt");

// 使用 while 循环和 getline() 函数逐行读取文件
while (getline (MyReadFile, myText)) {
  // 从文件中输出文本
  cout << myText;
}

// 关闭文件
MyReadFile.close(); 运行实例 »

0 人点赞过