pc016.c (2305B)
1 /* Write a c program that records book data from user and stores them in to a file. */ 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 #include <stdbool.h> 7 8 #define FILENAME "Library.txt" 9 10 typedef struct Book 11 { 12 int id; 13 char title[20]; 14 char author[20]; 15 }Book; 16 17 void dataInput(Book *, int); 18 void displayData(Book *, int); 19 bool writeLog(Book *, int); 20 21 int main() 22 { 23 Book book[3]; 24 int choice; 25 26 printf("== Enter the data =="); 27 dataInput(book, 3); 28 printf("\n\n Data enetered by the user =="); 29 displayData(book, 3); 30 31 if (writeLog(book, 3)) 32 { 33 printf("\n\nSuccessfully written the log into \"%s\"", FILENAME); 34 return 0; 35 } else 36 { 37 printf("\nError writing log."); 38 return 1; 39 } 40 } 41 42 void dataInput(Book *book, int n) 43 { 44 int i; 45 char *p; 46 47 for (i = 0; i < n; i++) 48 { 49 printf("\nEnter the Book ID: "); 50 if (scanf("%d", &book[i].id) != 1) 51 { 52 printf("\nError reading bookID."); 53 exit(1); 54 } 55 while (getchar() != '\n') 56 ; 57 58 printf("Enter the Book Title: "); 59 if (fgets(book[i].title, sizeof(book[i].title), stdin) == NULL) 60 { 61 printf("\nError reading title."); 62 exit(1); 63 } 64 p = strchr(book[i].title, '\n'); 65 if (p) 66 *p = '\0'; 67 68 printf("Enter the Book Author: "); 69 if (fgets(book[i].author, sizeof(book[i].author), stdin) == NULL) 70 { 71 printf("\nError reading Author."); 72 exit(1); 73 } 74 p = strchr(book[i].author, '\n'); 75 if (p) 76 *p = '\0'; 77 } 78 } 79 80 void displayData(Book *book, int n) 81 { 82 int i; 83 for (i = 0; i < n; i++) 84 { 85 printf("\n\nBook ID: %d" 86 "\nBook Title: %s" 87 "\nBook Author: %s", 88 book[i].id, book[i].title, book[i].author); 89 } 90 } 91 92 bool writeLog(Book *book, int n) 93 { 94 int i; 95 FILE *output = NULL; 96 output = fopen(FILENAME, "w"); 97 if (output == NULL) 98 { 99 printf("\n\nError writing file \"%s\"", FILENAME); 100 return false; 101 } 102 for (i = 0; i < n; i++) 103 { 104 fprintf(output, "%d \'%s\' \'%s\'\n", book[i].id, book[i].title, book[i].author 105 } 106 fclose(output); 107 return true; 108 }