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