I’m trying to take words from a text file to a linked list.
FILE *f = fopen("test.txt","r");
while (fgets( line, sizeof(line), f ))
for (word = strtok(line, " "); word; word = strtok(NULL, " "))
{
temp->data=word;
temp->next=(node *) malloc(sizeof(node));
printf("%s\n",word); // this prints the words correctly
temp=temp->next;
}
But when I list the words from the beginning of the linked list, they are incorrect. I think its about strtok?
You’re reading lines of your file into a single buffer that gets reused for each line —
line.strtokreturns a pointer into the buffer it operates on.You store the result of
strtokinto your linked list without making a copy of the string.When you read the next line, that pointer still points at the same place in the line, but now there’s different data in that line. You won’t get what you expect.
To fix it you need to copy (with
strcpyor something similar) the result into a buffer in your linked list. If you havestrdupavailable, you might want to use that.