c - 逐行读入链表

标签 c linked-list fgets

我想将文本文件中的每一行放在链表中的一个节点中。我已经设法逐行写出文本,但是当我尝试将行存储在一个节点中时,所有节点中只保存了文本的最后一行。知道我做错了什么吗?

#include <stdio.h>
#include <stdlib.h>

struct list
{
    char *line;
    struct list *next;
};

int main(void)
{
    FILE *f;
    f = fopen("text.txt", "r");
    if (f == NULL) exit("ERROR\n");

    struct list n1, n2, n3, n4;
    struct list *pointer = &n1;

        n1.line = NULL;
        n1.next = &n2;
        n2.line = NULL;
        n2.next = &n3;
        n3.line = NULL;
        n3.next = &n4;
        n4.line = NULL;
        n4.next = 0;

    int nodenr = 0;

    int buf[50];
    while(fgets(buf, sizeof(buf), f) != NULL)
    {
        printf("%s", buf);
        ++nodenr;
        if (nodenr == 1)
        {
            n1.line = buf;
        }
        else if (nodenr == 2)
        {
            n2.line = buf;
        }
        else if (nodenr == 3)
        {
            n3.line = buf;
        }
        else if (nodenr == 4)
        {
            n4.line = buf;
        }
    }

    while (pointer != 0)
    {
        printf("%s\n", pointer->line);
        pointer = pointer->next;
    }
    fclose(f);
}

最佳答案

出现问题是因为所有节点的行指针都指向 buf 缓冲区,因此所有节点都将包含您读入的最后一行。

您必须在读取每个节点时为每个节点分配缓冲区的副本,而不是缓冲区指针本身。

关于c - 逐行读入链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25743887/

相关文章:

C 结构初始化 - 有趣

c++ - 一个通用的双向链表,创建链表时赋值错误

c - 打印链表的float元素显示不正确?

c - 我们是否需要显式关闭写端已经关闭的管道的读端?

c - fgets 未读取整行,未遇到新行字符

c - 如何在for循环中输入if语句?

c++ - "-x c"后返回 native 文件处理

c - 不知道为什么我在这里遇到段错误

c - 插入排序链表

C - 如果最大长度大于 50,则返回变量始终为空