my code compiles and runs, but loads 0 words into the dictionary. Can you spot what's wrong with it? (As a sample, I tried using the smaller dictionary with a random text file. example syntax: "./speller dictionaries/small texts/alice.txt").
#include <stdbool.h>
#include "dictionary.h"
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
//alpha + "'"
#define alphabet 27
//create nodes
typedef struct _node
{
bool is_word;
struct _node* children[alphabet];
}
node;
void freenode(node* leaf);
node* root;
unsigned int dic_size = 0;
bool load(const char* dictionary)
{
FILE* inptr = fopen(dictionary, "r");
if (inptr == NULL)
{
printf("Could not open dictionary.\n");
return false;
}
//create parent node
root = malloc(sizeof(node));
if (root == NULL)
{
return false;
}
//initialize children pointers to 0
for (int i = 0; i < alphabet; i++)
{
root->children[i] = NULL;
}
unsigned int dic_size = 0;
//leave root intact, set another pointer called leaf as traversal of children
node* leaf = root;
//commence scan of dictionary until end
while (!feof(inptr))
{
char c = fgetc(inptr);
int alphaplace;
if (c != '\n')
{
//special case for apostrophe
if (c == '\'')
{
alphaplace = 26;
}
else
{
alphaplace = c - 'a';
}
if (leaf->children[alphaplace] == NULL)
{
//create new node
leaf->children[alphaplace] = malloc(sizeof(node));
if (leaf == NULL)
{
return false;
}
leaf = leaf->children[alphaplace];
//initialize new node pointers to null
for (int j = 0; j < alphabet; j++)
{
leaf->children[j] = NULL;
}
}
else
{
leaf = leaf->children[alphaplace];
}
}
//else when word is terminated with "\n" set the leaf pointer to true
else
{
if (leaf != root)
{
leaf->is_word = true;
dic_size++;
leaf = root;
}
}
}
fclose(inptr);
return true;
}