好的!既然你提到了 C++ 的文件输入输出库 <fstream>,我将为你详细讲解它的用法,包括基本概念、核心类和函数,以及一些实用的代码示例。<fstream> 是 C++ 标准库中用于处理文件操作的头文件,配合 <iostream> 可以实现从文件读取数据或将数据写入文件的功能。以下是完整的内容,适合初学者和进阶用户学习。


C++ 文件输入输出库:<fstream>

<fstream> 提供了处理文件的工具,主要用于:

  • 读取文件:从文件中提取数据。
  • 写入文件:将数据保存到文件中。
  • 文件管理:创建、打开、关闭文件等。

核心类

<fstream> 定义了以下三个主要类(都继承自 <iostream> 的基类):

  1. std::ofstream:输出文件流,用于写入文件(output file stream)。
  2. std::ifstream:输入文件流,用于读取文件(input file stream)。
  3. std::fstream:通用文件流,既可读也可写(file stream)。

包含头文件

#include <fstream>
#include <iostream> // 通常配合使用

基本操作步骤

  1. 声明文件流对象:选择适合的类(ofstreamifstreamfstream)。
  2. 打开文件:使用 open() 函数指定文件名和模式。
  3. 读写操作:用 <<(写入)或 >>(读取),或使用其他方法如 getline()
  4. 关闭文件:用 close() 释放资源(析构时会自动关闭,但手动关闭是好习惯)。

文件打开模式

打开文件时,可以指定模式(std::ios 中的标志):

  • std::ios::in:打开文件用于读取(ifstream 默认)。
  • std::ios::out:打开文件用于写入(ofstream 默认)。
  • std::ios::app:追加模式,写入数据追加到文件末尾。
  • std::ios::trunc:截断模式,打开时清空文件内容(默认与 out 一起使用)。
  • std::ios::binary:二进制模式(非文本模式)。
  • 组合使用:用 | 运算符,如 std::ios::in | std::ios::out

示例代码

1. 写入文件 (ofstream)

#include <fstream>
#include <iostream>

int main() {
    std::ofstream outFile; // 创建输出文件流对象
    outFile.open("example.txt"); // 打开文件(默认覆盖模式)

    if (outFile.is_open()) { // 检查是否成功打开
        outFile << "Hello, this is a test file.\n"; // 写入数据
        outFile << "Number: " << 42 << std::endl;
        outFile.close(); // 关闭文件
        std::cout << "Data written to file successfully.\n";
    } else {
        std::cerr << "Error: Unable to open file.\n";
    }

    return 0;
}
  • 运行后,会在程序目录下生成 example.txt,内容为两行文本。
  • is_open() 检查文件是否成功打开,避免操作失败。

2. 读取文件 (ifstream)

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

int main() {
    std::ifstream inFile("example.txt"); // 直接在构造时打开文件

    if (inFile.is_open()) {
        std::string line;
        while (std::getline(inFile, line)) { // 逐行读取
            std::cout << line << std::endl; // 输出到控制台
        }
        inFile.close();
    } else {
        std::cerr << "Error: Unable to open file.\n";
    }

    return 0;
}
  • std::getline() 从文件中读取一行,直到文件末尾。
  • 如果 example.txt 不存在,打开会失败。

3. 读写文件 (fstream)

#include <fstream>
#include <iostream>

int main() {
    std::fstream file("data.txt", std::ios::in | std::ios::out | std::ios::trunc); // 读写模式,清空文件

    if (file.is_open()) {
        // 写入
        file << "Age: 25\n";
        file << "Name: Alice\n";

        // 将文件指针移回开头
        file.seekg(0, std::ios::beg);

        // 读取
        std::string line;
        while (std::getline(file, line)) {
            std::cout << line << std::endl;
        }

        file.close();
    } else {
        std::cerr << "Error: Unable to open file.\n";
    }

    return 0;
}
  • seekg() 用于移动读取指针(g 表示 get),seekp() 用于移动写入指针(p 表示 put)。
  • std::ios::beg 表示从文件开头计算偏移。

4. 追加模式写入

#include <fstream>
#include <iostream>

int main() {
    std::ofstream outFile("log.txt", std::ios::app); // 追加模式

    if (outFile.is_open()) {
        outFile << "New log entry at " << __TIME__ << "\n"; // 追加当前时间
        outFile.close();
        std::cout << "Log appended.\n";
    } else {
        std::cerr << "Error: Unable to open file.\n";
    }

    return 0;
}
  • __TIME__ 是预定义宏,输出编译时的当前时间。
  • 追加模式不会覆盖原有内容。

注意事项

  1. 错误处理:总是检查 is_open() 或用 fail() 判断文件操作是否成功。
  2. 文件路径:相对路径基于程序运行目录,绝对路径需写全(如 C:\\test.txt)。
  3. 缓冲区:写入时数据可能暂存缓冲区,close()flush() 可强制写入。
  4. 二进制模式:处理非文本数据时(如图片),用 std::ios::binary

小练习

以下是一个基于 <fstream> 的练习题,你可以尝试回答:

问题:

写一个 C++ 程序,提示用户输入一段文字,将其保存到文件 note.txt 中,然后再从文件中读取并显示内容。

参考答案(你可以先尝试)

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

int main() {
    // 写入文件
    std::ofstream outFile("note.txt");
    if (!outFile.is_open()) {
        std::cerr << "Error opening file for writing.\n";
        return 1;
    }
    std::cout << "Enter some text: ";
    std::string text;
    std::getline(std::cin, text);
    outFile << text << std::endl;
    outFile.close();

    // 读取文件
    std::ifstream inFile("note.txt");
    if (!inFile.is_open()) {
        std::cerr << "Error opening file for reading.\n";
        return 1;
    }
    std::string line;
    std::cout << "File content:\n";
    while (std::getline(inFile, line)) {
        std::cout << line << std::endl;
    }
    inFile.close();

    return 0;
}

下一步

  • 如果你想试试这个练习,请写下你的代码,我会帮你检查并反馈。
  • 如果你想要更复杂的示例(比如处理二进制文件、异常处理),或者围绕 <fstream> 设计测验题,请告诉我!
  • 你也可以直接提出具体问题,比如“如何读取 CSV 文件?”或“怎么处理大文件?”。

现在,你想做什么?试试练习,还是有其他想法?