跳到内容

文件输入与输出 ​

#include <fstream> 提供文件 I/O:std::ofstream(写文件)、std::ifstream(读文件)、std::fstream(读写皆可)。它们都派生自 iostream 体系,所以你学过的 <<、>>、getline、流状态检查等全部适用——文件流只是把"目的地/来源"从控制台换成磁盘文件。

写文本文件 ​

用 std::ofstream 打开文件,把 << 作用于流对象即可写入:

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

int main()
{
    std::ofstream fout("notes.txt");
    if (!fout.is_open()) {
        std::cerr << "无法打开文件\n";
        return 1;
    }

    fout << "学习笔记\n";
    fout << "今日要点:文件 I/O\n";
    fout << "累计天数:" << 17 << "\n";

    fout.close();          // 显式关闭,确保缓冲刷盘
    std::cout << "已写入 notes.txt\n";
    return 0;
}

打开文件后务必检查 is_open() 或直接对流对象判真假(失败时为假)。close() 会自动刷新缓冲并释放资源;虽然析构也会关闭,但显式 close() 能更早释放文件锁,推荐养成习惯。

读文本文件 ​

std::ifstream 配合 >> 或 getline 读取:

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

int main()
{
    std::ifstream fin("notes.txt");
    if (!fin) {                      // 流对象可直接判真假
        std::cerr << "打不开文件\n";
        return 1;
    }

    // 方式一:逐词读取(遇空白分割)
    std::string word;
    while (fin >> word)
        std::cout << "[" << word << "]\n";

    // 方式二:逐行读取(保留行内空格)
    fin.clear();                     // 清掉上一次读到 EOF 的失败标志
    fin.seekg(0);                    // 回到文件开头
    std::string line;
    while (std::getline(fin, line))
        std::cout << "行:" << line << "\n";

    fin.close();
    return 0;
}

while (fin >> word) 和 while (std::getline(fin, line)) 都依赖"读取失败时流变假"来终止循环。读到文件尾会触发 eofbit,循环自然结束。

打开模式 ​

open(或构造函数)的第二参数指定打开模式,可用位或 | 组合:

模式含义
std::ios::in读
std::ios::out写
std::ios::app追加,每次写定位到末尾
std::ios::ate打开时定位到末尾(可移动)
std::ios::trunc打开时清空已有内容
std::ios::binary二进制模式,不做行尾转换
cpp
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    const char* path = "log.txt";

    // 追加模式:不清空,每次写到文件尾
    std::ofstream app(path, std::ios::out | std::ios::app);
    app << "新增一行\n";
    app.close();

    // 读取验证
    std::ifstream fin(path);
    std::string line;
    while (std::getline(fin, line))
        std::cout << line << "\n";
    fin.close();
    return 0;
}

默认规则:ofstream 默认 out | trunc(打开即清空);ifstream 默认 in;fstream 默认 in | out。想保留原内容追加,必须显式加 app。

命令行参数与多文件处理 ​

main 可以接收命令行参数,写文件处理工具时常用:

cpp
#include <iostream>
#include <fstream>
#include <cstdlib>

int main(int argc, char* argv[])
{
    if (argc < 2) {
        std::cerr << "用法:" << argv[0] << " 文件1 文件2 ...\n";
        return 1;
    }

    long grandTotal = 0;
    for (int i = 1; i < argc; ++i) {
        std::ifstream fin(argv[i]);
        if (!fin.is_open()) {
            std::cerr << "打不开 " << argv[i] << "\n";
            continue;             // 跳过坏文件,继续处理其余
        }
        long count = 0;
        char ch;
        while (fin.get(ch))       // 一个字符一个字符数
            ++count;
        std::cout << argv[i] << ":" << count << " 字符\n";
        grandTotal += count;
        fin.clear();              // 清 EOF,便于复用流对象
        fin.close();
    }
    std::cout << "合计 " << grandTotal << " 字符\n";
    return 0;
}

argc 是参数个数(含程序名本身,所以从 argv[1] 开始才是用户传的文件),argv 是参数字符串数组。复用一个流对象处理多个文件时,每次 open 前要 clear() 清除上次留下的 EOF/失败标志。

流的复用与状态恢复 ​

同一个流对象可以反复打开不同文件,但失败标志会"粘住"——不清除就无法再次打开:

cpp
#include <iostream>
#include <fstream>

int main()
{
    std::ifstream fin;
    fin.open("不存在.txt");      // 失败
    if (!fin)
        std::cout << "第一次打开失败\n";

    fin.open("notes.txt");        // 即使文件存在,因 failbit 还在,仍会失败
    if (!fin)
        std::cout << "第二次也失败(状态没清)\n";

    fin.clear();                  // 清除失败标志
    fin.open("notes.txt");
    if (fin.is_open())
        std::cout << "清除后成功打开\n";
    fin.close();
    return 0;
}

记忆口诀:复用流对象先 clear()。这是处理多文件、循环读写时的高频坑。

课后练习 ​

  1. 写后读:用 std::ofstream 写入几行文字到一个文件,关闭后用 std::ifstream 重新打开逐行打印。验证 close() 之后内容确实落盘。
  2. 追加 vs 截断:分两次运行程序,第一次用默认模式写文件,第二次分别用 app 和默认模式再写。每次运行后查看文件内容,体会 trunc(默认)和 app 的差别。
  3. 多文件统计:仿照本节示例,写一个接受命令行多个文件名的程序,统计每个文件的行数和总行数。提示:用 std::getline 循环计数。
  4. 状态恢复:写一个程序,先用一个 std::ifstream 打开一个不存在的文件名,确认它失败;接着 clear() 后打开一个真实文件,确认它能成功。理解为什么不清状态就打不开。