欢迎来到程序员中文网!

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

C++ 文件流与序列化:读写文本与二进制数据

时间:2026年08月12日 05:42:24 浏览:1

C++ 文件流与序列化:读写文本与二进制数据


文件流是 C++ 标准库中实现文件 I/O 的核心组件。


1. 文本读写


#include <fstream>
#include <string>

// 写入
std::ofstream out("data.txt");
out << "Hello" << 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. 序列化技巧


使用第三方库(如 Boost.Serialization、protobuf)可简化复杂对象的序列化。


4. 异常处理


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

文件操作务必检查状态,避免未定义行为。