开发者

About: strtok function

开发者 https://www.devze.com 2023-01-29 19:45 出处:网络
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 ))

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 correctl开发者_开发百科y
            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.

strtok returns a pointer into the buffer it operates on.

You store the result of strtok into 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 strcpy or something similar) the result into a buffer in your linked list. If you have strdup available, you might want to use that.


You're setting temp->data to the word pointer. This does not copy the word. strtok() changes the buffer and since you're only pointing at the word and not copying it, you see those changes also.

Make a copy of word if you want to keep it around.


It's not strtok. You're not copying each word to some other location. So you are keeping pointers to the word within line then the next call to fgets overwrites the data pointed to with the next line of characters


Your linked list stores pointers to the same memory area, namely line, which gets updated at every newline.

You should allocate memory for each word, with malloc() and use strcpy() for making a copy of word.


The word is a pointer to strtok's internal buffer.

The solution is to allocate temp->data to hold enough chars currently stored in the word string, and then do a strcpy

0

精彩评论

暂无评论...
验证码 换一张
取 消