[英]How to get data read into linked list from text file in C
I'm pretty new to C programming and I am trying to build a console application that takes in some user survey data into a singly linked list and generates statistics out of it. 我对C编程非常陌生,我正在尝试构建一个控制台应用程序,该程序将一些用户调查数据纳入一个单链表并从中生成统计信息。
The main idea is that every time application user opens up the application, the existing survey data is loaded from text file into linked list nodes. 主要思想是,每次应用程序用户打开应用程序时,现有的调查数据都会从文本文件加载到链接列表节点中。 User can then manipulate data as they want.
然后,用户可以根据需要操纵数据。
My issue is that application crashes every time the importList function is called and I can't figure out where my issue is. 我的问题是,每次调用importList函数时,应用程序都会崩溃,而我无法弄清楚问题出在哪里。 I would be really grateful if anyone can point out where my mistake is.
如果有人能指出我的错误所在,我将不胜感激。 Thank you.
谢谢。
Here is the function for importing data from text file: 这是从文本文件导入数据的功能:
void importList(struct nodeList** head)
{
//set up the linked list node by node
struct nodeList *temp;
temp =(struct nodeList*)malloc(sizeof(struct nodeList));
temp = *head;
//open survey data file in read mode to import existing survey data
openSurveyFile();
//read in data that's in the text file to nodes in linked list
while(!feof(surFPtr))
{
//import data from file. All data except address is held in single word lines.
fscanf(surFPtr, "%d", &temp->PPS);
fscanf(surFPtr, "%s", temp->name);
fscanf(surFPtr, "%s", temp->surname);
fgets(temp->address, 50, surFPtr);//since address is a multiword string the list needs to read the entire line
fscanf(surFPtr, "%s", temp->eMail);
fscanf(surFPtr, "%d", &temp->age);
fscanf(surFPtr, "%d", &temp->income);
fscanf(surFPtr, "%s", temp->gender);
fscanf(surFPtr, "%d", &temp->exercise);
fscanf(surFPtr, "%d", &temp->alcohol);
fscanf(surFPtr, "%d", &temp->smoking);
fflush(stdin);
//allocate memory for the next node in list
temp->next =(struct nodeList*)malloc(sizeof(struct nodeList));
temp = temp->next;//move on to next node
}
//close survey data file once all data is imported
closeSurveyFile();
}//end of importList function
There is an error near the beginning: you are losing the memory allocated first into temp
since you are replacing temp
with *head
. 开头附近有一个错误:您正在丢失首先分配给
temp
的内存,因为您正在用*head
替换temp
。 If *head
is null when you call this function, you get an exception when you dereference the pointer. 如果在调用此函数时
*head
为null,则在取消引用指针时会遇到异常。 Maybe you want to do *head = temp;
也许你想做
*head = temp;
instead, to get the head of your list back? 相反,要重新获得列表的头?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.