欢迎来到程序员中文网!

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

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

时间:2026年08月12日 05:34:29 浏览:0

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


文件流(fstream)支持文本和二进制文件的读写。


1. 文本读写


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

2. 二进制读写


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));

3. 错误处理


std::ifstream in('notexist.txt');
if (!in.is_open()) {
std::cerr << 'Failed to open file!' << std::endl;
return -1;
}

流操作符可方便地处理基本类型和自定义类型。