答案是使用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()函数将结构体内容以二进制形式写入文件:
立即学习“C++免费学习笔记(深入)”;
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_castzuojiankuohaophpcnconst char*youjiankuohaophpcn(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_castzuojiankuohaophpcnchar*youjiankuohaophpcn(students), sizeof(students));
// 检查是否成功读取全部数据
if (file.gcount() != sizeof(students)) {
std::cerr << "读取数据不完整!\n";
} else {
for (int i = 0; i < 3; ++i) {
std::cout zuojiankuohaophpcnzuojiankuohaophpcn "姓名: " zuojiankuohaophpcnzuojiankuohaophpcn students[i].name
zuojiankuohaophpcnzuojiankuohaophpcn ", 年龄: " zuojiankuohaophpcnzuojiankuohaophpcn students[i].age
zuojiankuohaophpcnzuojiankuohaophpcn ", 成绩: " zuojiankuohaophpcnzuojiankuohaophpcn students[i].score zuojiankuohaophpcnzuojiankuohaophpcn "\n";
}
}
file.close();}
完整使用示例
在
main函数中调用写入和读取函数:
int main() {
writeBinary(); // 先写入数据
readBinary(); // 再读取验证
return 0;
}
执行后会输出:
姓名: Alice, 年龄: 20, 成绩: 88.5 姓名: Bob, 年龄: 21, 成绩: 92 姓名: Charlie, 年龄: 19, 成绩: 76.5基本上就这些。注意二进制操作依赖数据结构的内存布局,跨平台或涉及复杂类型时需谨慎处理对齐和字节序问题。对于
std::string等动态类型,不能直接写入,需转换为固定格式。简单结构体和POD类型最适合这种方式。










