Adventures in C — Understanding fread() and fwrite()

Ryan McGovern
2 min readOct 7, 2018

In my previous article, I shared the code from Zed A Shaws Learn C the Hard Way, exercise 17. In an attempt at better understanding this code I want to break down the exercise into smaller parts. One thing that confused me in the exercise was how fread() and fwrite() are used to read and write the database.

Here is a simpler program that first writes some data to a file, then reads it and prints it out.

What I’ve done here is created a small program that creates a new Book struct then sets its properties using the arguments supplied on the command line. We then open the file and write these properties in binary format, close it, open it again for reading and print out the values. Here’s how to run it:

make books

./books 1 mybook 432

And the output would look like the following:

ID: 1

Title: mybook

Number of pages: 432

Not too bad. I did what I set out to do, but what I’d really like is to be able to add multiple records to the database file. This was something I didn’t fully understand from the previous example. This program overwrites the previous data every time it’s run.

I’d also like to abstract away some of the functionality into functions, set the filename as an argument, and add more stringent checks to make sure that a user doesn’t input “bad” data.

I’ll write another version of this program soon. In the meantime, please feel free to leave a comment.

--

--

Ryan McGovern

An ordinary guying learning the C programming language.