This week I will be walking through the implementation of the Load function from CS50 problem set 5. If you need information on the implementation of the Check function, please refer to last week’s post. Next week I will dig into the Unload function and the Size function. So, let’s dig into this function.

The first thing we want to do is set a pointer to a new file that is read only and in that file we will put our dictionary. By this time in the course, the syntax should look very familiar. The next item is to ensure that the file we just opened does, in fact, have some data. So, we test to see if the file is null. If it is null, we return an error message to the user. We next set a buffer in which the index is set to the length of the word plus one. The addition of the one is so that we can add the null terminator to the end of the word when we load the dictionary.  Next, we set n equal to the length plus two, so that the fgets function that we call will stop when n-1 characters are read.

Next, we implement a while loop that uses the fgets function as a condition, and will loop through until the function returns null. The fgets function will read each line from the input stream (the dictionary file that we opened) untill the end of the file. Now we can add the null terminator to the end of the word and pass it into our hash function, just as we did in the Check function. Now we need to create a node pointer and allocate memory that is the size of the node. This node is what we will use the traverse the dictionary. If the node is null, we will close the file and return false, as we failed to load the dictionary.

We now implement the strcpy function that will copy the word in our buffer into a linked list using the hashing function. It will then continue on to the next word in the dictionary. Now each time that our while loop executes, we want to increment our word count variable. This variable is what we will use when we call the Size function. Remember, that whenever we open a file we must close it as well. So, when the while loop is finished, we close the file and return true to the program.

And that is it for the implementation of the Load function from problem set 5. Stay tuned for next week when I will be going over the implementation of the Unload function. If you found this post helpful, remember to share it on your favorite social media site by clicking one or more of the buttons below. If you have any questions, post them in the comment section. As always…Happy Programming!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s