tags:

views:

57

answers:

5

I want to write a unix/linux program, that will use a configuration file.

My problem is, where should I put the location of the file?

I could "hardcode" the location (like /etc) into the program itself.

However, I would like it, if the user without privileges could install it (through make) somewhere else, like ~.

Should the makefile edit the source code? Or is it usually done in a different way?

+5  A: 

Create some defaults:

  • /etc/appname
  • ~/.appname

Then if you want to allow these to be overridden have your application inspect an environment variable. e.g.

  • $app_userconfig
  • $app_config

Which would contain an override path/filename.

Lastly add a command line option that allows a config to be specified at runtime, e.g.

  • -c | --config {filename}
slomojo
A: 

As skaffman says, the canonical locations for things like config files are specified in FHS. There appears to be a convention that a program will read a config file from the directory from which it is run as an alternative to the one in the hard-coded location. You may wish to consider adding a command-line switch that allows a user to specify an alternative config file location, as well.

Darael
+1  A: 

keeping a global config file under /etc/prgname is a standard. Also allowing a .local config file for individual users that will override the global settings would allow each user to personalize the program to their preference.

cmptrwhz
A: 

The makefile shouldn't modify the source directly, but it can pass a folder path/name to the compiler through the -D option. One way to handle it would be to #define something like DEFAULT_PATH to be the default installation path. If the user wants to define a path, the makefile would add -DUSER_PATH=whatever to the compiler options. You would write your code to use USER_PATH if it exists, and DEFAULT_PATH otherwise.

bta
+1  A: 

It is common to use a series of places to get the location:

  1. Supplied by the user as a command line argument (i.e. ./program -C path/to/config/file.cfg).
  2. From an environment variable (char *path_to_config = getenv("PROGRAMCONFIG");).
  3. Possibly look for a user specific or local version (stat("./program.cfg") or build up a strig to specify either "$HOME/.program/config.cfg" or "$HOME/.program.cfg" and stat that).
  4. Hardcoded as a backup (stat("/etc/program/config.cfg",...)).
dmckee