Bojana B Bojana B - 3 months ago 17
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?

while(1){

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

tree=insert(tree,string,x);
}

Answer

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) {
        break;
    }
    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);
}