繁体   English   中英

如何将数据从C中的文本文件读入链接列表

[英]How to get data read into linked list from text file in C

我对C编程非常陌生,我正在尝试构建一个控制台应用程序,该程序将一些用户调查数据纳入一个单链表并从中生成统计信息。

主要思想是,每次应用程序用户打开应用程序时,现有的调查数据都会从文本文件加载到链接列表节点中。 然后,用户可以根据需要操纵数据。

我的问题是,每次调用importList函数时,应用程序都会崩溃,而我无法弄清楚问题出在哪里。 如果有人能指出我的错误所在,我将不胜感激。 谢谢。

这是从文本文件导入数据的功能:

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

开头附近有一个错误:您正在丢失首先分配给temp的内存,因为您正在用*head替换temp 如果在调用此函数时*head为null,则在取消引用指针时会遇到异常。 也许你想做*head = temp; 相反,要重新获得列表的头?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM