MST

星途 面试题库

面试题:C语言结构体文件I/O中等难度题

假设有一个结构体如下:struct Student { char name[20]; int age; float score; }; 请编写代码,将若干个Student结构体实例写入到一个二进制文件中,然后再从该文件中读取并打印出这些结构体信息。
34.0万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#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;
}