C 将数据从.dat文件传输到LinkedList
我试图从dat文件(“boot.dat”)中读取数据,并将其放入图书对象的链接列表中 在我的程序结束时,LinkedList数据被写入文件 在这个函数中,文件被打开,然后一个if语句检查文件是否存在(如果不存在,则表示程序从未运行过,然后用户输入10本书) else运行代码将数据从文件传输到linkedList。这是我的尝试。当我运行代码显示所有传入的书籍时,它会给我一个错误“分段错误(核心转储)” 这是函数的代码。希望有人能发现我的错误C 将数据从.dat文件传输到LinkedList,c,io,linked-list,segmentation-fault,C,Io,Linked List,Segmentation Fault,我试图从dat文件(“boot.dat”)中读取数据,并将其放入图书对象的链接列表中 在我的程序结束时,LinkedList数据被写入文件 在这个函数中,文件被打开,然后一个if语句检查文件是否存在(如果不存在,则表示程序从未运行过,然后用户输入10本书) else运行代码将数据从文件传输到linkedList。这是我的尝试。当我运行代码显示所有传入的书籍时,它会给我一个错误“分段错误(核心转储)” 这是函数的代码。希望有人能发现我的错误 //file data input function v
//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 transferred...\n\n");
}
}
//文件数据输入函数
void fileInput()
{
//打开文件
fp=fopen(“账簿日期”,“r”);
如果(fp==NULL)
{
printf(“\n\n无法打开文件book.dat\n”);
printf(“\n**********************数据库为空。需要手动输入书籍***************\n\n\n\n\n”);
对于(int i=0;i<10;i++)
{
printf(“\n第%d本,共10本:\n”);
printf(“-----------------------\n”);
addBook();
}
}否则
{
//确定第一本书的大小
firstBook=(结构节点*)malloc(sizeof(结构节点));
结构节点*currentBook=firstBook;//使第一条记录等于当前记录
结构节点*newBook=(结构节点*)malloc(sizeof(结构节点));
while(1)//无尽的while循环。最后一个节点中的NULL指针结束循环
{
fread(currentBook,sizeof(structbookdata),1,fp);
if(currentBook->next==NULL)//NULL表示列表结束
打破
currentBook->next=newBook;//指针引用下一个节点
currentBook=newBook;//新建当前记录
}
printf(“\n\n文件数据已成功传输…\n\n”);
}
}
您应该会收到来自编译器的警告。你在用什么编译器?@user3386109我在用哈佛的CS50设备,在cmd终端上编译。嗯,好吧,你需要阅读手册,找到命令行选项,上面写着“给我所有可能的警告”。(对于visual studio,它是-W4
。对于gcc和clang,它是-Wall
)使用最大警告设置,查找并修复所有警告。如果有一些警告您不理解,或不知道如何修复,请在此处询问(提供完整准确的警告文本)。如果编译时出现了最大的警告,而代码没有生成任何警告,那么您需要得到一个真正的编译器。struct节点是什么?什么是结构bookData
?为什么它们不是相同的数据类型?您没有列出足够的代码来确定问题。尽管我会说您已经有一个bug,即您使用模式“r”
打开文件,但您应该使用模式“rb”
,因为您似乎正在读取/写入二进制数据。