1
0

fwrite.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. struct Book {
  5. char title[50];
  6. char author[50];
  7. float price;
  8. };
  9. struct FileHeader {
  10. char magic[4];
  11. int version;
  12. int count;
  13. };
  14. int main() {
  15. int num_books = 5;
  16. struct Book *books = (struct Book *)malloc(num_books * sizeof(struct Book));
  17. memset(books, 0, num_books * sizeof(struct Book));
  18. // 填充模拟数据
  19. for (int i = 0; i < num_books; i++) {
  20. sprintf(books[i].title, "C Programming Vol.%d", i + 1);
  21. sprintf(books[i].author, "Author %d", i + 1);
  22. books[i].price = 30.0f + i;
  23. }
  24. // 准备文件头
  25. struct FileHeader header = {{'B', 'O', 'O', 'K'}, 1, num_books};
  26. // 以二进制写入模式打开文件
  27. FILE *fp = fopen("books.dat", "wb");
  28. if (!fp) {
  29. perror("文件打开失败");
  30. free(books);
  31. return 1;
  32. }
  33. // 1. 写入文件头
  34. fwrite(&header, sizeof(struct FileHeader), 1, fp);
  35. // 2. 一次性写入所有书籍数据 (效率极高)
  36. fwrite(books, sizeof(struct Book), num_books, fp);
  37. printf("二进制数据已成功保存至 books.dat\n");
  38. fclose(fp);
  39. free(books);
  40. return 0;
  41. }