来自文本文件的信息,在代码中解析,未存储到链表中

Info from text file, parsed in the code, not being stored into the linked list

我有打开、读取和关闭文本文件的功能:

void readDataFile()
{
    FILE *fp = fopen("AssignmentOneInput.txt", "r"); //opens AssignmentOneInput.txt for reading
    char buffer[100];
    char *insertName;
    char *id;

    if (fp == NULL)
    {
        printf("Error while opening the file.\n");
        exit(0);
    }

    while (!feof(fp))
    {
        fgets(buffer, sizeof buffer, fp);
        insertName = strtok(buffer, ",");
        id = strtok(NULL, ",");
        insertNode(insertName, id); //function right here is supposed to input information
                                    //into the linked list
    }
    fclose(fp);
}

这是我的插入函数:

void insertNode(char *insertName, char *id)
{
    struct node *temp = malloc(sizeof(struct node));

    int intId = atoi(id);

    strcpy(temp->name, insertName);
    temp->id = intId;
    temp->next = head; //rest of the new list is entirety of the current list
    head = temp; //head of the new list is the element being inserted
}

我从文本文件中读取信息。我使用 strtok 将信息解析为标记并将它们存储到各自的变量中。然后,我在 while (!feof(fp)) 循环的末尾调用 insertNode 将每行信息存储到链表中。但是,不会存储信息。

每当我在主函数中调用 insertNode 并通过它 运行 时,信息就会毫无问题地存储到链表中。

所以我现在的想法是,要么是解析影响了信息的存储,要么是我的 insertNode 函数有问题。

谁能给我解释一下这是为什么?

对您现有代码的一些改动

while (fgets(buffer, sizeof buffer, fp) != NULL)
{
    insertName = strtok(buffer, ",");
    id = strtok(NULL, ",");
    if(insertName != NULL && id != NULL)
    insertNode(insertName, id);                                 
}