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