1
0

booksave.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /* booksave.c -- saves structure contents in a file */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #define MAXTITL 40
  6. #define MAXAUTL 40
  7. #define MAXBKS 10 /* maximum number of books */
  8. char * s_gets(char * st, int n);
  9. struct book { /* set up book template */
  10. char title[MAXTITL];
  11. char author[MAXAUTL];
  12. float value;
  13. };
  14. int main(void)
  15. {
  16. struct book library[MAXBKS]; /* array of structures */
  17. int count = 0;
  18. int index, filecount;
  19. FILE * pbooks;
  20. int size = sizeof (struct book);
  21. if ((pbooks = fopen("book.dat", "a+b")) == NULL)
  22. {
  23. fputs("Can't open book.dat file\n",stderr);
  24. exit(1);
  25. }
  26. rewind(pbooks); /* go to start of file */
  27. while (count < MAXBKS && fread(&library[count], size,
  28. 1, pbooks) == 1)
  29. {
  30. if (count == 0)
  31. puts("Current contents of book.dat:");
  32. printf("%s by %s: $%.2f\n",library[count].title,
  33. library[count].author, library[count].value);
  34. count++;
  35. }
  36. filecount = count;
  37. if (count == MAXBKS)
  38. {
  39. fputs("The book.dat file is full.", stderr);
  40. exit(2);
  41. }
  42. puts("Please add new book titles.");
  43. puts("Press [enter] at the start of a line to stop.");
  44. while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL
  45. && library[count].title[0] != '\0')
  46. {
  47. puts("Now enter the author.");
  48. s_gets(library[count].author, MAXAUTL);
  49. puts("Now enter the value.");
  50. scanf("%f", &library[count++].value);
  51. while (getchar() != '\n')
  52. continue; /* clear input line */
  53. if (count < MAXBKS)
  54. puts("Enter the next title.");
  55. }
  56. if (count > 0)
  57. {
  58. puts("Here is the list of your books:");
  59. for (index = 0; index < count; index++)
  60. printf("%s by %s: $%.2f\n",library[index].title,
  61. library[index].author, library[index].value);
  62. fwrite(&library[filecount], size, count - filecount,
  63. pbooks);
  64. }
  65. else
  66. puts("No books? Too bad.\n");
  67. puts("Bye.\n");
  68. fclose(pbooks);
  69. return 0;
  70. }
  71. char * s_gets(char * st, int n)
  72. {
  73. char * ret_val;
  74. char * find;
  75. ret_val = fgets(st, n, stdin);
  76. if (ret_val)
  77. {
  78. find = strchr(st, '\n'); // look for newline
  79. if (find) // if the address is not NULL,
  80. *find = '\0'; // place a null character there
  81. else
  82. while (getchar() != '\n')
  83. continue; // dispose of rest of line
  84. }
  85. return ret_val;
  86. }