Bojana B Bojana B - 4 months ago 23
C Question

Fscanf that reads only a last word from a file

I'm trying to insert words from a file into a binary tree.The insert function works when not reading from a file also when I tried to print every read string after fscanf it it also works,but when I try to insert it into a tree only the last string from a file is read.Why does this happen?


if(fscanf(f,"%s %d",string,&x)==EOF)



insert() doesn't make a copy of the string, it just stores the pointer you give it in the tree. So all the tree entries contain a pointer to the same string, which you're overwriting each time you call fscanf.

The same problem happens with the x argument, you're passing the same pointer each time. You need to allocate a new int for each of the values as well.

while (1) {
    if (fscanf(f, "%s %d", string, x) == EOF) {
    char *new_str = malloc(strlen(string)+1);
    strcpy(new_str, string);
    int *new_int = malloc(sizeof(*x));
    *new_int = *x;
    tree = insert(tree, new_str, new_int);