c - 来自文本文件的信息,在代码中解析,不存储到链接列表中

标签 c insert 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);                                 
}

关于c - 来自文本文件的信息,在代码中解析,不存储到链接列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28391605/

相关文章:

php - 在没有日期插入的情况下重复插入到表中

c++ - 如何从文件重建 BST

c++ - 对双向链表 C++ 进行排序

arrays - 何时在数组/数组列表上使用链表?

c - 逻辑运算符、表达式和条件语句( bool 值)

检查硬盘是否在程序中处于事件状态

c - 为什么我的程序仅根据我向 Clang 提供源文件操作数的顺序而表现不同?

使用指针和数组正确调用函数

mysql - 从 tableB 插入 tableA where 条件集 case

mysql - 如果存在则更新记录,否则插入 MySQL