C++二进制文件读写实例教程
答案是使用std::ofstream和std::ifstream以std::ios::binary模式进行二进制文件读写。定义包含姓名、年龄和成绩的Student结构体,通过write()函数将数据写入文件,再用read()函数读回,确保数据完整性和正确性。
答案是使用std::ofstream和std::ifstream以std::ios::binary模式进行二进制文件读写。定义包含姓名、年龄和成绩的Student结构体,通过write()函数将数据写入文件,再用read()函数读回,确保数据完整性和正确性。

在C++中进行二进制文件的写入与读取,关键在于使用std::ofstream和std::ifstream并指定std::ios::binary模式。下面通过一个具体示例演示如何将自定义数据结构写入文件,并从文件中正确读回。
定义数据结构
假设我们要保存一组学生信息,包括姓名、年龄和成绩。先定义一个结构体:
struct Student {
char name[20];
int age;
float score;
// 构造函数方便初始化
Student(const char* n, int a, float s) {
strncpy(name, n, 19);
name[19] = '\0';
age = a;
score = s;
}
Student() = default; // 默认构造函数用于读取};
二进制写入文件
使用write()函数将结构体内容以二进制形式写入文件:
void writeBinary() {
std::ofstream file("students.dat", std::ios::binary);
if (!file) {
std::cerr << "无法打开文件进行写入!\n";
return;
}
Student s1("Alice", 20, 88.5f);
Student s2("Bob", 21, 92.0f);
Student s3("Charlie", 19, 76.5f);
// 一次性写入多个对象
Student students[] = {s1, s2, s3};
file.write(reinterpret_cast<const char*>(students), sizeof(students));
file.close();
std::cout << "数据已写入 students.dat\n";}
二进制读取文件
使用read()函数将数据从文件中读出,注意内存布局需与写入时一致:
void readBinary() {
std::ifstream file("students.dat", std::ios::binary);
if (!file) {
std::cerr << "无法打开文件进行读取!\n";
return;
}
Student students[3];
file.read(reinterpret_cast<char*>(students), sizeof(students));
// 检查是否成功读取全部数据
if (file.gcount() != sizeof(students)) {
std::cerr << "读取数据不完整!\n";
} else {
for (int i = 0; i < 3; ++i) {
std::cout << "姓名: " << students[i].name
<< ", 年龄: " << students[i].age
<< ", 成绩: " << students[i].score << "\n";
}
}
file.close();}
完整使用示例
在main函数中调用写入和读取函数:
int main() {
writeBinary(); // 先写入数据
readBinary(); // 再读取验证
return 0;
}
执行后会输出:
姓名: Alice, 年龄: 20, 成绩: 88.5 姓名: Bob, 年龄: 21, 成绩: 92 姓名: Charlie, 年龄: 19, 成绩: 76.5基本上就这些。注意二进制操作依赖数据结构的内存布局,跨平台或涉及复杂类型时需谨慎处理对齐和字节序问题。对于std::string等动态类型,不能直接写入,需转换为固定格式。简单结构体和POD类型最适合这种方式。
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















