Help! i'm completely stuck is this code.
After using a lot of gdb, i found out that when the end of file is reached the for loop (for(letter = fgetc(inptr); letter != '\n'; letter =fgetc(inptr)) //as long as not end of word iterate over word) keeps looping even though "letter" is then -1. The while loop that comes before the for loop doesn't seem to notice that the end of file is reached, printing out c wil always give 97 (a). Please help.
bool load(const char* dictionary)
{
root = malloc(sizeof(node)); //malloc space for first node struct in the heap
node* currentNode = NULL; //node poiter called currentNode poits to NULL
FILE *inptr = fopen(dictionary, "r"); //open dictionary file for reading
if (inptr == 0) //if the inptr does not point to file
{
printf("Error\n"); //display error message
}
int letter;
int c;
while ((c = fgetc(inptr)) != EOF)
{
fseek(inptr, -1, SEEK_CUR);
currentNode = root; //currentNode pointer points to root
for(letter = fgetc(inptr); letter != '\n'; letter =fgetc(inptr)) //as long as not end of word iterate over word
{
if(currentNode->children[(int)letter-93] == NULL) //if current node has no children
{
currentNode->children[(int)letter-93] = malloc(sizeof(node)); //create new node and let current note point to it
currentNode = currentNode->children[(int)letter-93]; //make the new node the current node
}
else
{
currentNode = currentNode->children[(int)letter-93]; //make the current node the next node
}
}
currentNode->is_word = true; //if the previous for loop is not true, \n is found and current node is_word is set to true
wordCount++; //+1 word count
}
currentNode = root;
fclose(inptr);
return true;
}