0

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;
}

1 Answer 1

0

I don't understand your use of fseek, so basically what happens is when the for loop ends (i.e. you've reached /n marking end of word), the loop ends, and fseek is called, so you move the file pointer back to the previous position. You will never move on to the next word. Not sure why you included it, but GDB should have shown you how the loop kept on getting repeated if you'd used the command n (next) to go through it line by line.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .