#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 50
#define STUDENT_COUNT 3
// 定义学生结构体
typedef struct {
char name[MAX_NAME_LENGTH];
int age;
float score;
} Student;
int main() {
Student students[STUDENT_COUNT] = {
{"Alice", 20, 85.5},
{"Bob", 21, 90.0},
{"Charlie", 22, 78.0}
};
FILE *file = fopen("students.bin", "wb");
if (file == NULL) {
perror("无法打开文件用于写入");
return 1;
}
// 将学生信息写入二进制文件
if (fwrite(students, sizeof(Student), STUDENT_COUNT, file) != STUDENT_COUNT) {
perror("写入文件失败");
fclose(file);
return 1;
}
fclose(file);
// 从二进制文件读取学生信息
file = fopen("students.bin", "rb");
if (file == NULL) {
perror("无法打开文件用于读取");
return 1;
}
Student readStudents[STUDENT_COUNT];
size_t readCount = fread(readStudents, sizeof(Student), STUDENT_COUNT, file);
if (readCount != STUDENT_COUNT) {
perror("读取文件失败");
fclose(file);
return 1;
}
fclose(file);
// 打印读取的学生信息
for (int i = 0; i < STUDENT_COUNT; i++) {
printf("姓名: %s, 年龄: %d, 成绩: %.2f\n", readStudents[i].name, readStudents[i].age, readStudents[i].score);
}
return 0;
}