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