Hello, I am new to the forum. I need help in debugging the program as it does not produce the expected output and I can't figure out where goes wrong. I haven't completed the whole program and I am working on it part by part.
Here is my code:
Code:
#include <stdio.h>#include <stdlib.h>
#include <string.h>
struct book
{
char *title;
char *author;
char *subject;
};
struct library
{
struct book collection;
int num_books;
struct library *next;
};
typedef struct library lib;
typedef lib *libPtr;
void addBook(FILE *fPtr,libPtr *sPtr);
void copybook(struct book *dest,struct book *source);
void deleteBook(FILE *fPtr,libPtr *sPtr);
void searchBook(FILE *fPtr,libPtr *sPtr);
void listAuthor(FILE *fPtr,libPtr *sPtr);
void listSubject(FILE *fPtr,libPtr *sPtr);
int main()
{
libPtr startPtr = NULL;
int choice;
FILE *fPtr;
fPtr = fopen("library.txt","r");
if (fPtr == NULL)
{
puts("File can't be loaded.\n");
}
else
{
while (!feof(fPtr))
{
fscanf(fPtr,"%d",&choice);
switch (choice)
{
case 1:
addBook(fPtr,&startPtr);
break;
}
}
}
fclose(fPtr);
return 0;
}
void addBook(FILE *fPtr,libPtr *sPtr)
{
libPtr newPtr;
libPtr currentPtr;
libPtr previousPtr;
struct library *myLib;
myLib = (struct library *)malloc(sizeof(struct library));
myLib->collection.title = (char *)malloc(sizeof(50));
myLib->collection.author = (char *)malloc(sizeof(50));
myLib->collection.subject = (char *)malloc(sizeof(50));
fscanf(fPtr,"%s%s%s",myLib->collection.title,myLib->collection.author,myLib->collection.subject);
newPtr = malloc(sizeof(lib));
if (newPtr != NULL)
{
newPtr->collection = myLib->collection;
newPtr->next = NULL;
while (currentPtr != NULL)
{
previousPtr = currentPtr;
currentPtr = currentPtr->next;
}
if (previousPtr == NULL)
{
newPtr->next = *sPtr;
*sPtr = newPtr;
}
else
{
previousPtr->next = newPtr;
newPtr->next = currentPtr;
}
}
else
{
puts("No memory available.\n");
}
}