-
-
Save anonymous/46862cf0cb3d0372bfcb2954070f24fa to your computer and use it in GitHub Desktop.
dictionary.c - shared from CS50 IDE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Loads dictionary into memory. Returns true if successful else false. | |
*/ | |
bool load(const char *dictionary) | |
{ | |
// allocating space for root node | |
root = calloc(1, sizeof(node)); | |
// assigning node pointer "temp" | |
temp = root; | |
fd = fopen(dictionary, "r"); | |
// ensuring filepointer points to our dictionary | |
if (fd == NULL) | |
{ | |
fprintf(stderr, "Could not load dictionary.\n"); | |
return 1; | |
} | |
else | |
{ | |
// iterates over the entire dictionary file | |
for (int ch = fgetc(fd); ch != EOF; ch = fgetc(fd)) | |
{ | |
/**converts chars to corresponding array spots | |
* skipping node[0] to avoid conflict with '\0' null terminators | |
* and skipping node[10] by assigning 'j'/10 to the end of | |
* the alphabet to avoid conflict with /n ASCII values | |
*/ | |
if (isalpha(ch)) | |
{ | |
ch = ch - 96; | |
if (ch == 10) | |
{ | |
ch = 27; | |
} | |
} | |
// assigning apostrophe characters to the end of the array | |
else if (ch == '\'') | |
{ | |
ch = 28; | |
} | |
// if the corresponding slot in the node is NULL | |
if (temp -> paths[ch] == NULL) | |
{ | |
/** the end of a dictionary word | |
* set the node bool to true and | |
* reset the pointer to the root | |
*/ | |
if (ch == '\n') | |
{ | |
temp -> validword = true; | |
temp = root; | |
} | |
// otherwise we're in the middle of a word | |
else | |
{ | |
// call memory for a new node and have the slot in temp point to the new node | |
temp->paths[ch] = calloc(1, sizeof(node)); | |
// temp pointer moves to new node | |
temp = temp -> paths[ch]; | |
} | |
} | |
// if the corresponding slot is already open | |
else if (temp -> paths[ch] != NULL) | |
{ | |
// temp pointer moves to the next node | |
temp = temp -> paths[ch]; | |
} | |
} | |
/** dictionary is loaded, so return pointer to the start | |
* of the file to prepare for spell check and return true | |
*/ | |
fseek(fd, 0, SEEK_SET); | |
return true; | |
} | |
// otherwise nothing was loaded and return false | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment