One-liner C library for reading INI/configuration files under Linux
A settings file (or INI file) is a good alterative to requiring an infinitely long set of command line arguments. There are lots of libraries for this but you've never seen one as simple as this one, because it leverages preexisting tools: bash and getenv(), but with a tiny downside.
First, bash makes it easy to use a plain text file to set some environmental variables. The syntax is simple:
a_number=5
a_string=example # no spaces allowed unless quoted though
You don't pollute your environment by temporarily loading the script inside another script that calls your program:
#!/bin/bash
source mySettings.ini
myApp "$@"
Then to load the environmental variables use the c standard getenv function (here's my wrapper that accepts default values):
#include <stdlib.h>
float getenvf(char * name, float def )
{char * r = getenv(name); return (r==0) ? def : atof(r);}
Use it like this:
refreshRate = getenf("refresh_rate", 59.94);
The only downside is that your program must be called by a script. I've found no clean way to have child process spawn bash and be able to read back the environment variables. If you want to read strings you'll need to use both malloc and strcpy which is a bit more than a one-liner but still way simpler than most INI libraries.
Comments