C++ 文件读写

文本文件的读写操作主要通过标准库头文件\<fstream> 提供的 std::ifstream(输入文件流)、std::ofstream(输出文件流)和 std::fstream(读写文件流)来实现。

常见操作包括打开文件、读写内容、关闭文件等。

文本文件读写

头文件与命名空间:

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

写文本文件:

ofstream ofs("test.txt"); // 打开文件,默认覆盖写入
if (!ofs) {
    cout << "文件打开失败" << endl;
} else {
    ofs << "Hello, world!" << endl;
    ofs << "C++文件写入示例" << endl;
    ofs.close(); // 关闭文件
}

读文本文件:

ifstream ifs("test.txt");
if (!ifs) {
    cout << "文件打开失败" << endl;
} else {
    string line;
    while (getline(ifs, line)) { // 按行读取
        cout << line << endl;
    }
    ifs.close();
}

追加写入:

ofstream ofs("test.txt", ios::app); // 以追加方式打开
ofs << "追加内容" << endl;
ofs.close();

常用注意事项:

• 文件流对象创建时可直接指定文件名,也可用 .open() 方法后续打开。
• 读写完成后应及时调用 .close() 关闭文件
• 可通过 is_open() 判断文件是否成功打开。
• 读写失败时应检查文件路径、权限等问题。

二进制文件读写

二进制文件读写,需要结合 ios::binary 模式实现。与文本文件不同,二进制文件直接读写原始字节数据,适合存储结构体、图片、音频等非文本数据。

写文件:

#include <fstream>

struct Data {
    int id;
    double value;
};

int main() {
    Data d = {42, 3.14};
    std::ofstream ofs("data.bin", std::ios::binary);
    if (!ofs) {
        std::cout << "文件打开失败" << std::endl;
        return 1;
    }
    ofs.write(reinterpret_cast<const char*>(&d), sizeof(d));
    ofs.close();
    return 0;
}

读文件:

#include <fstream>

struct Data {
    int id;
    double value;
};

int main() {
    Data d;
    std::ifstream ifs("data.bin", std::ios::binary);
    if (!ifs) {
        std::cout << "文件打开失败" << std::endl;
        return 1;
    }
    ifs.read(reinterpret_cast<char*>(&d), sizeof(d));
    ifs.close();
    std::cout << "id: " << d.id << ", value: " << d.value << std::endl;
    return 0;
}

关键点说明:

• 打开文件时需加 std::ios::binary 标志,防止平台自动转换换行符等。
• 读写用 write() 和 read(),参数为指向数据的指针和字节数。
• 结构体中如有指针或虚函数表指针,直接读写会有问题,建议只用于POD类型(Plain Old Data)。
• 读写前后应检查文件是否成功打开。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值