I don´t know what may be happening with my code. When I run it without any dictionaries it runs (although is also not able to open cat.txt), but when I try to run it using small it could not load it.
// Implements a dictionary's functionality
#include <stdbool.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include "dictionary.h"
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Number of buckets in hash table
const unsigned int N = 1;
// Hash table
node *table[N];
// Returns true if word is in dictionary else false
bool check(const char *word)
{
//Create a copy of the word
char word_copy[LENGTH + 1];
for (int i = 0; i < strlen(word); i++)
{
word_copy[i] = tolower(word[i]);
}
//Initialize hashed word
unsigned int h = hash(word_copy);
//Sets pointer
node *cursor = table[h];
//Check if word in dictionary
while (cursor != NULL)
{
if (strcasecmp(word_copy, cursor->word) == 0)
{
return true;
}
else
{
cursor = cursor->next;
}
}
return false;
}
// Hashes word to a number (hash function from delipity post on reddit)
unsigned int hash(const char *word)
{
// TODO
unsigned int hash_value = 0;
int n = strlen (word);
for (int i = 0; i < n; i++)
{
hash_value = (hash_value << 2) ^ word[i];
}
return hash_value % N;
}
//Initializes counter for words in dictionary
int word_count = 0;
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// Opens dictionary
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
return false;
}
//Read strings
char word[LENGTH + 1];
while (fscanf (file, "%s", word) != EOF)
{
//Allocates node for each word
node *n = malloc (sizeof(node));
if (n == NULL)
{
unload();
return false;
}
//Copy word if true
strcpy(n->word, word);
//Calculate index of word
int h = hash(n->word);
//Initialize head of hash table
node *head = table[h];
//Isert new node at the beginning
if (head == NULL)
{
table[h] = n;
word_count++;
}
else
{
n->next = table[h];
table[h] = n;
word_count++;
}
}
fclose(file);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
// TODO
return word_count;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
node *head = NULL;
node *cursor = head;
while (cursor != NULL)
{
node *temp = cursor;
cursor = cursor->next;
free(temp);
}
return true;
}