First, the while
loop is not comparing titles in the file and the num_books
does not add on top of the file. Second, instead of reading the num_books
already in the file, it reads twice every time executed. can someone help?
typedef struct book {
char *title;
char *author;
char *subject;
};
struct library {
struct book collection;
int num_books;
struct library *next;
};
add(FILE *file, FILE *fileout, struct library *thislib, struct book *thisbook) {
char choice = "1";
int size;
char line1[50];
file = fopen("temp1.txt", "a+");
fileout = fopen("temp2.txt", "a+");
printf("\t Add a book to your library!\n");
printf("\t\t Title: ");
scanf("%s", &thisbook->title);
printf("\t\t Author: ");
scanf("%s", &thisbook->author);
printf("\t\t Subject: ");
scanf("%s", &thisbook->subject);
fseek(file, 0, SEEK_SET);
thislib->num_books++;
fprintf(file, "%d", thislib->num_books);
size = ftell(file);
while (thislib->num_books > 1) {
for (int i = 1; i < size; i++) {
fseek(file, i, SEEK_CUR);
fscanf(file, "%s", line1);
printf("%s", line1);
if (strcmp(thisbook->title, line1) != 0) {
printf("Please re-enter title as similar ones are not allowed.\n");
printf("\t\t Title: ");
scanf("%s", &thisbook->title);
strcpy(line1, "");
}
}
}
fseek(file, 1, SEEK_SET);
fprintf(file, "%c %s %s %s\n", choice, &thisbook->title, &thisbook->author, &thisbook->subject);
fprintf(fileout, "The book %s, author %s, subject %s has been added to the library.\n", &thisbook->title, &thisbook->author, &thisbook->subject);
fclose(file);
fclose(fileout);
}