简体   繁体   中英

What is the simplest way for my C program to receive some file paths from configuration?

I have an application that is currently configurable via command line arguments

myprog  -fooFile 'foo.txt' -barFile 'bar.txt'

Command line parameters are a bit cumbersome so I want to allow for other avenues for these configurations but I am a bit disappointed that its looking more complicated then it taught it should be.

Solution 1: Use environment variables

I could make my program look for MYPROG_FOO_FILE and MYPROG_BAR_FILE envorinment variables. The implementation is just a getenv but env variables are global and add clutter and are also hard to configure. Specially for GUI apps because many window managers don't source ".profile" during initialization.

Solution 2: Use a configuration file

Since the fooFile and progFile are kind of static configuration values, it seems like its better to put those in a configuration file somewhere:

fooFile = /home/hugomg/foo.txt
barFile = /home/hugomg/bar.txt

But afaik there is no easy way in C to read an arbitrarily long string from a file. Do I really need to make a loop that keeps reallocing a buffer just for this?

Alternatively, since all my values are file names, is there some #define somewhere specifying the maximum size of a path string?

Your configuration file approach with a simple syntax looks good to me.

Since you are on Linux, you could use getline to read the file. It can handle lines of arbitrary length and manages the memory allocation for you.

If your application has a GUI, you may want your user to configure it from within the application. In this case, you may want to use a database to store your configuration; that way you can validate your data on it's way in, so your user can't write a bad config file. I would suggest using SQLite for this: it provides a full database in a file, and is pretty easy to use.

http://www.sqlite.org/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM