forked from AllenDowney/ExercisesInC
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ec3c51d
commit a98028f
Showing
1 changed file
with
59 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
#include <string.h> | ||
#include <ctype.h> | ||
#include <glib.h> | ||
|
||
#define MAXCHAR 10000 | ||
|
||
char* itoa(int num) { | ||
char* str = malloc(sizeof(char) * MAXCHAR); | ||
sprintf(str, "%d", num); | ||
return str; | ||
} | ||
|
||
void updateHashtable(GHashTable* hash, char* key) { | ||
char* val = g_hash_table_lookup(hash, key); | ||
if (val == NULL) { | ||
g_hash_table_insert(hash, key, "1"); | ||
} else { | ||
int new_val = atoi(val) + 1; | ||
g_hash_table_replace(hash, key, itoa(new_val)); | ||
} | ||
} | ||
|
||
GHashTable* createHashtable() { | ||
GHashTable* hash = g_hash_table_new(g_str_hash, g_str_equal); | ||
return hash; | ||
} | ||
|
||
void readFile(GHashTable* hash, char* fileName) { | ||
FILE *f = fopen(fileName, "r"); | ||
|
||
if (f == NULL) { | ||
printf("Could not open the given file: %s\n", fileName); | ||
return; | ||
} | ||
|
||
char s[MAXCHAR]; | ||
while (fscanf(f, " %9999s", s) == 1) { | ||
for (int i = 0; i < MAXCHAR; i++) { | ||
s[i] = tolower(s[i]); | ||
} | ||
char* copy = g_strdup(s); | ||
updateHashtable(hash, copy); | ||
} | ||
} | ||
|
||
void printEntry(gpointer key, gpointer value, gpointer userdata) { | ||
printf("%s : %s\n", key, value); | ||
} | ||
|
||
int main () { | ||
GHashTable* hash = createHashtable(); | ||
readFile(hash, "pride_and_prejudice.txt"); | ||
printf("There are %d keys in the hash\n", g_hash_table_size(hash)); | ||
g_hash_table_foreach(hash, printEntry, NULL); | ||
g_hash_table_destroy(hash); | ||
return 0; | ||
} |