How to initialize a C program using a file, environment, and / or command line?

In C, how to configure the initial settings for a certain program using key-value pairs with any or all of them: plain text configuration file , environment variables and command line parameters. In addition, how to decide which method values ​​exceed those of the other two. Then, if the values ​​have been changed, it is not necessary to update the configuration file.

What is the easiest way to do this, and what, if any, are the most acceptable methods? Is there a small open source program that gives a good example of how this can be done?

+5
source share
6 answers

The basics:

  • To customize your program with environment variables, you can use the getenv function defined in stdlib.h.
  • To customize your program using command line arguments, declare your main function, for example, "int main (int argc, const char * const * argv)" and use a loop to view the arguments in the argv array. This size is set by argc.
  • To configure your program using a configuration file, it is advisable to choose some library for this, instead of inventing another format for a custom configuration file. Please note that depending on the platform you are targeting, there are also libraries for parsing command line arguments.

, , , , > > .

:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, const char* const* argv) {
    int i;
    const char* myConfigVar;

    // get default setting from environment
    myConfigVar = getenv("MY_CONFIG_VAR");

    // if the variable wasn't defined, initialize to hardcoded default
    if (!myConfigVar)
        myConfigVar = "default value";

    // parse commandline arguments
    // start at 1, because argv[0] contains the name of the program
    for (i = 1; i < argc; ++i) {
        if (strcmp("--my-config-var", argv[i]) == 0) {
            if (i + 1 < argc)
                myConfigVar = argv[i + 1];
            else
                printf("missing value for my-config-var argument\n");
        }
    }

    printf("myConfigVar = '%s'\n", myConfigVar);
    return 0;
}

, , , (), , , .

- , "" , , , . , .

+5

. XML INI . , , , . C INI , XML .

, "" . :

    • .

2 3 .

+2

. : " ?", " ?" " ?"?

( , unix):

  • ,

, , , , , ...

, , .

. , , ( ), :

  • , (, )
  • ( ?)
  • , .

unix getopt getopt_long. , gengetopt

, shell-, ( unix). - -, . , .


, , . , gengetopt, .

+2

Unix- Raymond "" " Unix ". ..

+1

Lua . Lua . " Lua", . 25 Lua C API Lua , .

+1

All Articles