In C: Reading a File Into a List
The normal method for reading a file in C is to define a buffer and load the file into an array. In this tutorial, we’re going to look at how to quickly load a file into a linked list so that we can handle files with an arbitrary amount of lines and unpredictable line length.
It’s been a couple years since I did any heavy lifting in C, so I decided to sit down in my spare time and really gain a master of it. To that end, I’m working on a small command-line application that searches through common log files for a given list of keywords. I’m no C guru, so I had a little fun figuring out how to handle a list of arbitrary length strings neatly. Here’s what I came up with.
Let’s get some necessary imports down:
If you would like to use dbg.h, head over to the github for it. It cleans up a lot of boilerplate we need to handle memory in C. Otherwise, feel free to edit the following sections with your own safety-checking scheme.
Defining the Linked List
Next, we need to define the linked list. Nothing here should be a surprise.
And a single method to create a node:
dbh.h verifies that we get a valid pointer, and redirects to the *error if we do not.
Reading the File
Now, we’re going to need a function to build the list.
We get a small boon from the fact that we don’t care about the file order. This function builds the list backwards compared to the file, but that saves us a few lines of code and doesn’t affect my end case. If you need the list to be in order, you would need to accomplish this like so:
Testing the Application
Let’s create some files and wrap this in a method to test it.
Then in the console:
My utility is called logfind, so then we have:
So there you have it- how to read a file line by line into a linked list in C. I hope you found this article helpful. Let me know what you think in the comments.