我正在尝试从dat文件中读取数据(“ boot.dat ”)并将其放入Book对象的LinkedList中。
在我的程序结束时,LinkedList数据被写入文件。
在此函数中打开文件,然后if语句检查文件是否存在(如果不存在,则表示程序从未运行过,然后用户输入10本书)
else运行代码将数据从文件传输到linkedList。那是我的尝试。当我运行代码来显示所有转移的书籍时,它会给我一个错误“ Segementation Fault(Core Dumped)”
这是函数的代码。希望有人能发现我的错误。提前谢谢。
//file data input function
void fileInput()
{
//open file
fp = fopen("book.dat", "r");
if (fp == NULL)
{
printf("\n\nCould not open the file book.dat\n");
printf("\n****************** The database is empty. Books will need to be manually entered ******************\n\n\n\n\n\n");
for(int i = 0; i < 10; i++)
{
printf("\n Book %d of 10:\n");
printf("----------------\n");
addBook();
}
}else
{
//sizing the first book
firstBook = (struct node *)malloc(sizeof(struct node));
struct node *currentBook = firstBook; //make first record equal current
struct node *newBook = (struct node *)malloc(sizeof(struct node));
while(1) //endless while loop. a NULL pointer in final node ends the loop
{
fread(currentBook,sizeof(struct bookData),1,fp);
if(currentBook->next == NULL) //NULL indicates end of list
break;
currentBook->next = newBook; //pointer referencing next node
currentBook = newBook; // make current record new
}
printf("\n\nFile data successfully transfered...\n\n");
}
}