0
点赞
收藏
分享

微信扫一扫

Python字典

infgrad 2023-05-10 阅读 121

#include <fstream> 是C++程序中常用的预处理指令,它包含了fstream库。这个库提供了用于处理文件输入/输出的类。fstream库主要包括以下几个类:

  1. std::ifstream:用于从文件读取数据的输入文件流类。
  2. std::ofstream:用于向文件写入数据的输出文件流类。
  3. std::fstream:用于同时进行文件的读取和写入操作的输入/输出文件流类。

以下是fstream库中的一些常用接口及用法:

打开文件:

  • ifstream file("filename.txt"):创建一个ifstream对象并打开名为filename.txt的文件以进行读取。
  • ofstream file("filename.txt"):创建一个ofstream对象并打开名为filename.txt的文件以进行写入。
  • fstream file("filename.txt"):创建一个fstream对象并打开名为filename.txt的文件以进行读取和写入。

关闭文件:

  • file.close():关闭与文件流关联的文件。

检查文件是否成功打开:

  • if (file.is_open()) { ... }:检查文件流是否成功打开文件。

从文件读取数据:

  • file >> variable:从文件流中读取数据并存储到变量中。
  • getline(file, line):从文件流中读取一整行数据并存储到line字符串中。

向文件写入数据:

  • file << data:将数据写入到文件流中。

检查文件流状态:

  • file.eof():检查文件流是否已到达文件末尾。
  • file.fail():检查文件流是否发生错误。
  • file.good():检查文件流是否处于良好状态,即没有发生错误,也没有到达文件末尾。

设置文件指针位置:

  • file.seekg(position):设置输入文件流的读取位置。
  • file.seekp(position):设置输出文件流的写入位置。

以下是一个简单的示例,演示如何使用ifstreamofstream类读取和写入文件:

#include <iostream>
#include <fstream>
#include <string>

int main() {
    // 创建并打开输入文件
    std::ifstream input_file("input.txt");
    if (!input_file.is_open()) {
        std::cerr << "Failed to open input file." << std::endl;
        return 1;
    }

    // 创建并打开输出文件
    std::ofstream output_file("output.txt");
    if (!output_file.is_open()) {
        std::cerr << "Failed to open output file." << std::endl;
        return 1;
    }

    // 读取输入文件的内容,并将其写入到输出文件中
    std::string line;
    while (getline(input_file, line)) {
        output_file << line << std::endl;
    }

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

    return 0;
}

这个示例程序从名为input.txt的文件中逐行读取内容,并将读取到的内容写入到名

举报

相关推荐

0 条评论