In this activity, we learn how to use iterator (e.g., hashtable_iterate(), counters_iterate()) to go through a hashtable and save its content to an external file.

Grab the starter code:

$ cp -r /thayerfs/courses/22fall/cosc050/workspace/activities/day19/iterator .
$ cd iterator/

save.c is the starter code where we created a hashtable and inserted dummy content. Our task is to fill in the to-do to write the hashtable content to an external file whose name is given in argv[1]. Save should write one line for each entry in the hashtable, as well as the documentID and count for each document that contains the word. The starter code makes one entry in the hashtable (for Dartmouth) and that entry appears in documentID 3 six times and documentID 4 eight times. We then expect one line written to a output file with Dartmouth followed by 3 6 4 8.

To compile the code, first generate the libcs50.a library under libcs50/, then use the library to generate the executable:

$ make -C libcs50/
make: Entering directory '/thayerfs/home/d84xxxx/cs50/activities/day19/iterator/libcs50'
cp libcs50-given.a libcs50.a
make: Leaving directory '/thayerfs/home/d84xxxx/cs50/activities/day19/iterator/libcs50'

Compile with

mygcc save.c libcs50/libcs50.a -o save

Once you are done, the program should run like this (here I save the content to a file named test):

$ ./save test
$ cat test 
Dartmouth: 3 6 4 8

Work in groups to finish the program. Use gdb and valgrind for debugging if necessary.

Solution

save-solution.c