Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
load function of PSET5 SPELLER
#include <stdbool.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include "dictionary.h"
int main (int argc, char *argv[])
{
FILE *open = fopen(argv[1],"r");
if (open == NULL)
{
fclose(open);
fprintf(stderr, "Can't open dictionary\n");
return false;
}
int index;
trie *root = malloc(sizeof(trie));
for (int i = 0; i < 27; i++) //initialization of struct
root->abc[i] = NULL;
root->isword = false;
trie *branch;
bool firstroot = false; //to track the first letter of a word (when true, I already have the beginning)
do //iterating over the dictionary
{
if (feof(open))
break;
for(char c = fgetc(open); c != '\n' && c !=EOF; c = fgetc(open)) //iterating over every word
{
if (c =='\'') //calculating the corresponding index for every letter
{
index = 26;
}
else
{
index = tolower(c) - 'a';
}
if (firstroot == false && root->abc[index] == NULL)
{
branch = malloc(sizeof(trie));
for (int i = 0; i < 27; i++) //initialization of struct
branch->abc[i] = NULL;
branch->isword = false;
root->abc[index] = branch;
firstroot = true;
}
else if (firstroot == false && root->abc[index] != NULL)
{
branch = root->abc[index];
firstroot = true;
}
else if (firstroot == true && branch->abc[index] == NULL)
{
branch->abc[index] = malloc(sizeof(trie));
branch = branch->abc[index]; //initialization of struct
for (int i = 0; i < 27; i++)
branch->abc[i] = NULL;
branch->isword = false;
}
else if (firstroot == true && branch->abc[index] != NULL)
{
branch = branch->abc[index];
}
}
firstroot = false; // After the word ends, I set this variable to false to track a new word
branch->isword = true; // And set true the last word
} while(true);
free(branch);
free(root);
fclose(open);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment