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)。
• 读写前后应检查文件是否成功打开。