首页 > 文章列表 > C++ 函数库中有哪些文件和路径类?

C++ 函数库中有哪些文件和路径类?

c++ 文件和路径类
495 2024-04-23

文件和路径类是 C++ 标准库中用于操作文件和路径的类。文件类包括 ifstream(读取文本文件)、ofstream(写入文本文件)、fstream(读写文本文件)、ofstream(写二进制文件)和 ifstream(读二进制文件)。路径类包括 path(表示文件或目录路径)和 directory_entry(表示文件系统条目信息)。在实际应用中,可以打开文件进行读取和写入,按行读取文件内容,并将内容写入其他文件。

C++ 函数库中有哪些文件和路径类?

C++ 函数库中的文件和路径类

C++ 标准库提供了许多用于操作文件和路径的文件系统库。下面介绍一些常用的类:

文件类

  • std::ifstream:用于读取文本文件。
  • std::ofstream:用于写入文本文件。
  • std::fstream:既可用于读取也可用于写入文本文件。
  • std::ofstream:用于写二进制文件。
  • std::ifstream:用于读二进制文件。

路径类

  • std::filesystem::path:表示文件或目录的路径。
  • std::filesystem::directory_entry:表示文件系统中条目的信息,包括文件、目录或符号链接。

实战案例

考虑以下场景:读取一个名为 "input.txt" 的文本文件的内容并将其写入 "output.txt" 文件。

#include <fstream>

int main() {
  // 打开 "input.txt" 文件进行读取
  std::ifstream input_file("input.txt");

  // 检查文件是否已成功打开 
  if (!input_file.is_open()) {
    // 文件未打开,处理错误
  }

  // 打开 "output.txt" 文件进行写入
  std::ofstream output_file("output.txt");

  // 检查文件是否已成功打开 
  if (!output_file.is_open()) {
    // 文件未打开,处理错误
  }

  // 从 "input.txt" 按行读取内容
  std::string line;
  while (std::getline(input_file, line)) {
    // 将读取的行写入 "output.txt"
    output_file << line << "n";
  }

  // 关闭文件
  input_file.close();
  output_file.close();

  return 0;
}