欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

C++ 文件读写与流操作详解

时间:2026年08月12日 04:46:50 浏览:2

文件流类



  • 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;
}

注意关闭文件或利用析构函数自动关闭,避免资源泄漏。