This is probably one of the most common tasks / problems when programming; You need to store the configuration of your application somewhere.
While I’m trying to create a webserver or other applications, I’d like to keep the code as clean as possible since my main interest in programming is architecture. This results in me wanting to store configurations in a file which can be changed without having to re-compile the software.
I’m not here to re-invent the wheel or anything like that, so what I’d like to do is creating a Configuration reader in C on *nix. The configuration might look a lot like any other software’s configuration; Apache, vsftpd, MySQL, etc.
The basic question is: How do you read from a textfile and process each line efficiently (in pure C)? Do I need to use fgetc() and process each char?
Okay, so let’s hit the other part. You need to think about what you’d like to have as your ‘language’. In the UNIX world, the sort of canonical version is probably whitespace-delimited text (think
/etc/hosts) or ‘:’ delimited text (like/etc/passwd).You have a couple of options, the simplest in some sense being to use scanf(3). Again, read the man page for details, but if a line entry is something like
then you’ll be looking for something like
You can get a bit more flexibility if you write a simple FSA parse: read characters one at a time from the line, and use a finite automaton to define what to do.