文件流类
ifstream:读文件ofstream:写文件fstream:读写
文本读写
#include <fstream>
#include <string>
// 写入
std::ofstream out("data.txt");
out << "Hello World" << std::endl;
out << 2025 << std::endl;
out.close();
// 读取
std::ifstream in("data.txt");
std::string line;
while (std::getline(in, line)) {
std::cout << line << std::endl;
}二进制读写
struct Record {
int id;
double score;
};
// 写入二进制
std::ofstream out("record.bin", std::ios::binary);
Record r = {1, 95.5};
out.write(reinterpret_cast<char*>(&r), sizeof(r));
// 读取二进制
std::ifstream in("record.bin", std::ios::binary);
Record r2;
in.read(reinterpret_cast<char*>(&r2), sizeof(r2));异常处理
std::ifstream in("notexist.txt");
if (!in.is_open()) {
std::cerr << "Failed to open file!" << std::endl;
return -1;
}注意关闭文件或利用析构函数自动关闭,避免资源泄漏。
