C++ | 文件读写(ofstream/ifstream/fstream)

一、C++文件操作核心类

C++标准库通过<fstream>提供了强大的文件操作支持,主要包含三个关键类:

类名 描述 典型用途
ofstream 输出文件流(Output File Stream) 文件写入操作
ifstream 输入文件流(Input File Stream) 文件读取操作
fstream 双向文件流(兼具读写功能) 需要同时读写的场景

二、常用API函数详解

1. 文件打开与关闭

cpp 复制代码
// 构造时直接打开文件
ifstream fin("data.txt", ios::in);
ofstream fout("output.txt", ios::out);

// 使用open方法
fstream file;
file.open("data.bin", ios::binary | ios::in);

// 检查是否打开成功
if (!fin.is_open()) {
    cerr << "文件打开失败!" << endl;
}

// 关闭文件
file.close();

文件打开模式:

模式标志 描述
ios::in 读模式(默认ifstream)
ios::out 写模式(默认ofstream),会清空原内容
ios::app 追加模式(写入内容到文件末尾)
ios::ate 打开后定位到文件末尾
ios::binary 二进制模式(默认是文本模式)
ios::trunc 截断文件(如果文件已存在)

2. 文本文件读写

写入示例:

cpp 复制代码
ofstream fout("log.txt");
if (fout) {
    fout << "当前时间: " << time(nullptr) << endl;
    fout << "状态: 正常运行" << endl;
    fout.close();
}

读取示例:

cpp 复制代码
ifstream fin("data.txt");
string line;
while (getline(fin, line)) {  // 逐行读取
    cout << line << endl;
}

3. 二进制文件操作

写入二进制数据:

cpp 复制代码
struct Person {
    char name[20];
    int age;
    double height;
};

Person p = {"张三", 25, 175.5};

ofstream fout("person.dat", ios::binary);
fout.write(reinterpret_cast<char*>(&p), sizeof(Person));

读取二进制数据:

cpp 复制代码
Person p;
ifstream fin("person.dat", ios::binary);
if (fin.read(reinterpret_cast<char*>(&p), sizeof(Person))) {
    cout << "姓名: " << p.name << endl
         << "年龄: " << p.age << endl
         << "身高: " << p.height << endl;
}

三、文件位置控制

cpp 复制代码
// 获取当前读位置
streampos pos = fin.tellg();

// 设置读位置(从文件开头偏移100字节)
fin.seekg(100, ios::beg);

// 设置写位置(从当前位置回退50字节)
fout.seekp(-50, ios::cur);

四、最佳实践建议

  1. RAII原则:利用构造函数自动打开,析构函数自动关闭

    cpp 复制代码
    { // 代码块开始
        ofstream tempFile("temp.txt");
        // 使用文件...
    } // 离开作用域自动关闭
  2. 异常处理:启用文件流异常

    cpp 复制代码
    file.exceptions(ios::failbit | ios::badbit);
    try {
        file.open("data.txt");
    } catch (const ios::failure& e) {
        cerr << "文件操作异常: " << e.what();
    }
  3. 状态检查:操作前验证流状态

    cpp 复制代码
    while (fin >> data) {  // 自动检测流状态
        // 处理数据
    }

五、完整示例代码

cpp 复制代码
#include <iostream>
#include <fstream>
#include <vector>

int main() {
    // 写入测试数据
    {
        ofstream fout("numbers.txt");
        for (int i = 1; i <= 100; ++i) {
            fout << i * i << endl;
        }
    } // 自动关闭文件

    // 读取并计算平均值
    ifstream fin("numbers.txt");
    double sum = 0;
    int count = 0;
    
    double num;
    while (fin >> num) {
        sum += num;
        count++;
    }

    cout << "平均值: " << sum / count << endl;
    return 0;
}

六、常见问题解答

Q:为什么我的文件内容没有保存?

A:确保文件正确关闭(显式调用close()或离开作用域)

Q:如何处理大文件(超过内存容量)?

A:采用分块读写的方式,避免一次性加载整个文件

Q:文本模式和二进制模式有什么区别?

A:在Windows系统中,文本模式会自动转换换行符(\r\n ↔ \n)

相关推荐
WL学习笔记33 分钟前
继承(C++)
c++·继承
lcj25111 小时前
【日志系统实战】同步/异步日志系统:手写日志等级模块,吃透enum class与7大分级,面试不慌
c++·设计模式·面试·c++11·日志系统
zmzb01031 小时前
C++课后习题训练记录Day216
数据结构·c++·算法
西西弗Sisyphus2 小时前
C++ 最小 Agentic Loop 实现 - 开始实现 完整的内容
开发语言·c++
天威?*3 小时前
团体程序设计天梯练习集L3-001 凑零钱
数据结构·c++
充值内卷4 小时前
Varsar:一个 5.7 MB 的免安装文件对比工具
c++·比较工具
wo_jack5 小时前
C++ 入门笔记(二十):stack / queue 的模拟实现 —— 适配器与 deque 底层
c++·stl·deque·queue·stack
_dindong5 小时前
仿muduo库实现高并发服务器 -通用类型Any类型的实现
服务器·c++
不在逃避q6 小时前
用生活里的小场景,一键打开 C++ 编程入门大门
开发语言·c++·生活
YSL0701246 小时前
C++string类详解
开发语言·数据结构·c++