You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将file.dat中的数据读取至新的Book结构体数组?

如何从二进制文件读取结构体数组到新的Book数组中

没问题,我来帮你搞定这个需求!既然你已经通过结构体数组把数据写入了BookMan.dat,那读取的时候直接用C标准库的fread函数就可以高效完成,它能一次性批量读取二进制数据到新的结构体数组里。

实现步骤&完整代码示例

我在你现有代码的基础上补充读取逻辑,你可以直接参考:

#include <stdio.h>
#include <stdlib.h>

#define Capacity 1000
struct Book{
    char BookID[10];
    char Title[100];
    char Author[50];
    float Price;
    int YearOfRelease;
} lstBook[Capacity];

int main() {
    FILE *infile;
    // 定义新的结构体数组,用来存储从文件读取的数据
    struct Book newBookList[Capacity];
    // 记录实际读取到的书籍数量
    size_t readCount;

    // 以二进制只读方式打开文件
    infile = fopen("C:\\Users\\Admin\\Desktop\\BookMan6\\BookMan.dat","rb");
    if (infile == NULL) {
        fprintf(stderr, "\nError opening BookMan.dat\n\n");
        exit(1);
    }

    // 关键:从文件读取数据到新数组
    // 参数说明:目标数组指针、单个结构体大小、最大读取个数、文件指针
    readCount = fread(newBookList, sizeof(struct Book), Capacity, infile);
    if (readCount == 0) {
        fprintf(stderr, "\nNo data read or error occurred\n\n");
    } else {
        printf("Successfully read %zu books from file:\n", readCount);
        // 可以循环打印读取到的数据验证
        for (size_t i = 0; i < readCount; i++) {
            printf("Book %zu:\n", i+1);
            printf("ID: %s\n", newBookList[i].BookID);
            printf("Title: %s\n", newBookList[i].Title);
            printf("Author: %s\n", newBookList[i].Author);
            printf("Price: %.2f\n", newBookList[i].Price);
            printf("Year: %d\n\n", newBookList[i].YearOfRelease);
        }
    }

    // 记得关闭文件,避免资源泄漏
    fclose(infile);
    return 0;
}

关键细节说明

  • fread的作用:它会按照你写入时的二进制格式,把文件里的字节直接映射到新的结构体数组中,保证数据的完整性,因为结构体的内存布局和写入时一致。
  • 读取数量校验:readCount会返回实际读取到的Book结构体个数,这个值可能小于Capacity(比如文件里的书籍数量本来就少于1000),后续操作要以这个实际数量为准,避免访问超出范围的数组元素。
  • 文件关闭:一定要记得用fclose关闭打开的文件,不然会造成文件资源泄漏。

如果你的写入操作是用fwrite(lstBook, sizeof(struct Book), bookCount, outfile);完成的(bookCount是当时写入的书籍数量),那上面的读取逻辑完全匹配,能准确还原所有数据。

内容的提问来源于stack exchange,提问作者Việt Nguyễn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:57:36