fread.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. // 保持结构体定义与写入时完全一致
  5. struct Book {
  6. char title[50];
  7. char author[50];
  8. float price;
  9. };
  10. struct FileHeader {
  11. char magic[4]; // 魔数 "BOOK"
  12. int version; // 版本号
  13. int count; // 书籍总数
  14. };
  15. int main() {
  16. FILE *fp = fopen("books.dat", "rb"); // "rb" 表示二进制读取模式
  17. // 1. 先读取文件头
  18. struct FileHeader header;
  19. if (fread(&header, sizeof(struct FileHeader), 1, fp) != 1) {
  20. printf("读取文件头失败!\n");
  21. fclose(fp);
  22. return 1;
  23. }
  24. // 3. 根据文件头里的 count 动态分配内存
  25. struct Book *books = (struct Book *)malloc(header.count * sizeof(struct Book));
  26. if (books == NULL) {
  27. printf("内存分配失败!\n");
  28. fclose(fp);
  29. return 1;
  30. }
  31. // 4. 一次性读取所有书籍数据
  32. // 从当前文件指针位置(文件头之后)开始读
  33. size_t read_count = fread(books, sizeof(struct Book), header.count, fp);
  34. if (read_count != (size_t)header.count) {
  35. printf("读取数据时发生错误,预期 %d 条,实际读取 %zu 条。\n", header.count, read_count);
  36. } else {
  37. // 5. 打印读取到的内容进行验证
  38. for (int i = 0; i < header.count; i++) {
  39. printf("ID: %d | 书名: %-20s | 作者: %-10s | 价格: %.2f\n",
  40. i + 1, books[i].title, books[i].author, books[i].price);
  41. }
  42. }
  43. // 6. 清理工作
  44. fclose(fp);
  45. free(books);
  46. books = NULL;
  47. return 0;
  48. }