confuse: simple.c

- Main Page
- Data Structures
- Files
- Examples

# simple.c

    00001 #include <string.h>
    00002 #include "confuse.h"
    00003
    00004 int main(void)
    00005 {
    00006     cfg_bool_t verbose = cfg_false;
    00007     char *server = NULL;
    00008     double delay = 1.356e-32;
    00009     char *username = NULL;
    00010
    00011     /* Although the macro used to specify an integer option is called
    00012      * CFG_SIMPLE_INT(), it actually expects a long int. On a 64 bit system
    00013      * where ints are 32 bit and longs 64 bit (such as the x86-64 or amd64
    00014      * architectures), you will get weird effects if you use an int here.
    00015      *
    00016      * If you use the regular (non-"simple") options, ie CFG_INT() and use
    00017      * cfg_getint(), this is not a problem as the data types are implicitly
    00018      * cast.
    00019      */
    00020     long int debug = 1;
    00021
    00022     cfg_opt_t opts[] = {
    00023         CFG_SIMPLE_BOOL("verbose", &verbose),
    00024         CFG_SIMPLE_STR("server", &server),
    00025         CFG_SIMPLE_STR("user", &username),
    00026         CFG_SIMPLE_INT("debug", &debug),
    00027         CFG_SIMPLE_FLOAT("delay", &delay),
    00028         CFG_END()
    00029     };
    00030     cfg_t *cfg;
    00031
    00032     /* set default value for the server option */
    00033     server = strdup("gazonk");
    00034
    00035     cfg = cfg_init(opts, 0);
    00036     cfg_parse(cfg, "simple.conf");
    00037
    00038     printf("verbose: %s\n", verbose ? "true" : "false");
    00039     printf("server: %s\n", server);
    00040     printf("username: %s\n", username);
    00041     printf("debug: %d\n", debug);
    00042     printf("delay: %G\n", delay);
    00043
    00044     printf("setting username to 'foo'\n");
    00045     /* using cfg_setstr here is not necessary at all, the equivalent
    00046      * code is:
    00047      *   free(username);
    00048      *   username = strdup("foo");
    00049      */
    00050     cfg_setstr(cfg, "user", "foo");
    00051     printf("username: %s\n", username);
    00052
    00053     /* print the parsed values to another file */
    00054     {
    00055         FILE *fp = fopen("simple.conf.out", "w");
    00056         cfg_print(cfg, fp);
    00057         fclose(fp);
    00058     }
    00059
    00060     cfg_free(cfg);
    00061
    00062     /* You are responsible for freeing string values. */
    00063     free(server);
    00064     free(username);
    00065
    00066     return 0;
    00067 }