I have implemented this for load. But if I execute the speller file in terminal, I get segmentation fault. I haven't implemented anything except for load as of now.
here it is:
//Trie Data Structure.
typedef struct node
{
bool isWord;
struct node* children[27];
}node;
//Make a new node function prototype.
node* newNode();
//Declaring it here so that the root is global. and all other global variables
char word[45+1];
node* root = NULL;
int length;
int c;
unsigned int index;
FILE* dictfp = NULL;
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char* word)
{
// TODO
return false;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char* dictionary)
{
//root is initailzed as a node.
root = newNode();
root->isWord = false;
length = strlen(dictionary);
//Open the dictionary
dictfp = fopen(dictionary, "r");
//return null if file can't be opened.
if (dictfp == NULL)
{
return false;
}
//a traversal pointer equal to root. We'll use only this traversal pointer.
node* trav = root;
//loop to iterate through all the words in the dictionary file.
while(!feof(dictfp))
{
fscanf(dictfp, "%s\n", word);
length = strlen(word);
for (int i = 0; i < length; i++)
{
c = word[i];
index = tolower(c) - 'a';
if (trav->children[index] == NULL)
{
node* newnode = newNode();
trav->children[index] = newnode;
}else if (trav->children[index] != NULL)
{
trav = trav->children[index];
}
if (c == '\n')
{
trav->isWord = true;
}
}
}
fclose(dictfp);
return true;
}
/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/
unsigned int size(void)
{
// TODO
return 0;
}
/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
bool unload(void)
{
// TODO
return false;
}
////Make a new node function
node* newNode()
{
node* newnode = calloc(1, sizeof(node));
//setting all children pointers to NULL.
for (int i = 0; i < 27; i++)
{
newnode->children[i] = NULL;
}
return newnode;
}
EDIT: I get "Could not open cat." in terminal if I use the small dictionary and cat as input. Could it be because of only having implemented Load so far.