I want to put each line in a text file in a node in a linked list. I have managed to write out the text line by line, but when I try to store the line in a node, only the last line of the text is saved in all the nodes. Any idea what I'm doing wrong?
#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);
}
Your problem occurs because all your nodes' line pointer point to the buf
buffer, so all will have the last line you read into it.
You have to assign a copy of the buffer for each node when you read it, not the buffer pointer itself.