Append a string from fscanf to linked list in C -
i want read file , put each words in linked list. when read file, linked list have number of nodes node equal last word.
an example, if text file :
hello sir
my linked list :
[sir,sir,sir]
and should :
[hello, good, sir]
my main.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> typedef struct nodetag { char *data; struct nodetag *next; } node; node *node_create(); typedef struct listtag { struct nodetag *first; } list; list *list_create(); void list_append(list *list, char *str); void list_print(list *list); int main(void) { char word[100]; file *file = fopen("file.txt", "r"); if(file == null) { printf("error in opening file\n"); return 1; } list *l = list_create(); while(fscanf(file, "%s", word) == 1){ list_append(l, word); } return 0; }
here functions. removed destroy , free functions make more clear.
node *node_create() { node *node = malloc(sizeof(node)); assert(node != null); node->data = ""; node->next = null; return node; } list *list_create() { list *list = malloc(sizeof(list)); assert(list != null); node *node = node_create(); list->first = node; return list; } void list_append(list *list, char *str) { assert(list != null); assert(str != null); node *node = list->first; while (node->next != null) { node = node->next; } node->data = str; node->next = node_create(); } void list_print(list *list) { assert(list != null); printf("["); node *node = list->first; while (node->next != null) { printf("%s", node->data); node = node->next; if (node->next != null) { printf(", "); } } printf("]\n"); }
if this, work properly. guess append pointer of word pointing same place again , again ?
list_append(l, "test1"); list_append(l, "test2");
output :
[test1, test2]
notice in main
, have 1 buffer storing strings:
char word[100];
you pass word
parameter list_append
method, during write
node->data = str;
this means of nodes pointing word
buffer in main
string, of them display same string.
to fix this, need duplicate buffer somewhere. i'd recommend doing this:
node->data = strdup(str);
there may other issues in code, you'll need fix before move on. try updating , see if resolves issue. @sean bright points out, seems you're overwriting wrong string pointers when append, you'll need fix well.
hope helps!
Comments
Post a Comment