-2

I'm very new to programming and I'm trying to load a dictionary from a text file to a linked list. I use a while loop for this but my code reads the last word twice (I also ran gdb to verify it). I guess something if my while condition is not working well but I cannot figure out why? Anyone can help me understand this?

Here is my code char* text = "small.txt";

// open the dictionary file
FILE* fp = fopen(text, "r");
if (fp == NULL)
{
    printf("Could not open %s.\n", text);
    // unload();
    return 1;
}

// temporary storage for current word
char curr_word [LENGTH + 1];

node * curr, * head;
head = NULL;

while (feof (fp) == 0)
{
    curr = malloc(sizeof(node));
    fscanf (fp, "%s", curr_word);
    strcpy (curr -> word, curr_word);
    curr -> next = head;
    head = curr;
}
ppfer
  • 33
  • 3
  • 5
    possible duplicate of ["while( !feof( file ) )" is always wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) - see in particular the second answer (from William Pursell) re 'enters the loop one more time than the author expects' – abligh Jan 30 '15 at 21:36
  • Just to summarise: `feof()` does not become true until *after* you failed to read from the file. It doesn't tell you the *next* read will be invalid. And, you didn't check the return value from `fscanf()`, or from `malloc()`. – Weather Vane Jan 30 '15 at 22:59

1 Answers1

0

Remove any empty new line at the end of the text file. If a new line character is present, one more iteration will be performed, fscanf will fail, and a new node containing the most recent text will be added.

Carmelix
  • 1
  • 3