liboptcfg
diff example/example.c @ 1:8fd2858c6a29
example (test) program
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Sat, 14 Nov 2015 14:12:30 +0200 |
parents | |
children | 9c73004c7af3 |
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/example/example.c Sat Nov 14 14:12:30 2015 +0200 1.3 @@ -0,0 +1,77 @@ 1.4 +#include <stdio.h> 1.5 +#include <stdlib.h> 1.6 +#include <optcfg.h> 1.7 + 1.8 +enum { 1.9 + OPT_FOO, 1.10 + OPT_BAR, 1.11 + OPT_XYZZY, 1.12 + OPT_HELP 1.13 +}; 1.14 + 1.15 +struct optcfg_option options[] = { 1.16 + /* short, long, id, description */ 1.17 + {'f', "foo", OPT_FOO, "foo does nothing really"}, 1.18 + {'b', "bar", OPT_BAR, "bar also does nothing"}, 1.19 + {0, "xyzzy", OPT_XYZZY, "xyzzy doesn't have a short option"}, 1.20 + {'h', "help", OPT_HELP, "print usage and exit"}, 1.21 + {0, 0, -1, 0} /* terminate with id=-1 */ 1.22 +}; 1.23 + 1.24 +int foo, bar; 1.25 +int xyzzy; 1.26 + 1.27 +int opt_handler(struct optcfg *oc, int opt, void *cls); 1.28 + 1.29 +int main(int argc, char **argv) 1.30 +{ 1.31 + /* pass the options array to initialize the optcfg object */ 1.32 + struct optcfg *oc = optcfg_init(options); 1.33 + /* set the option callback function */ 1.34 + optcfg_set_opt_callback(oc, opt_handler, 0); 1.35 + /* first let's load options from a config file */ 1.36 + printf("parsing config file: example.conf\n"); 1.37 + if(optcfg_parse_config_file(oc, "example.conf") == -1) { 1.38 + return 1; 1.39 + } 1.40 + /* then let's override those with commandline options */ 1.41 + printf("parsing commandline arguments\n"); 1.42 + if(optcfg_parse_args(oc, argc, argv) == -1) { 1.43 + return 1; 1.44 + } 1.45 + 1.46 + printf("\nfoo: %s\n", foo ? "true" : "false"); 1.47 + printf("bar: %s\n", bar ? "true" : "false"); 1.48 + printf("xyzzy: %d\n", xyzzy); 1.49 + 1.50 + optcfg_destroy(oc); 1.51 + return 0; 1.52 +} 1.53 + 1.54 +int opt_handler(struct optcfg *oc, int opt, void *cls) 1.55 +{ 1.56 + char *val; 1.57 + 1.58 + switch(opt) { 1.59 + case OPT_FOO: 1.60 + foo = 1; 1.61 + break; 1.62 + case OPT_BAR: 1.63 + bar = 1; 1.64 + break; 1.65 + case OPT_XYZZY: 1.66 + /* this option needs an integer value */ 1.67 + if(!(val = optcfg_next_value(oc)) || optcfg_int_value(val, &xyzzy) == -1) { 1.68 + fprintf(stderr, "xyzzy must be followed by a number\n"); 1.69 + return -1; 1.70 + } 1.71 + break; 1.72 + case OPT_HELP: 1.73 + /* print usage and exit */ 1.74 + printf("Usage: example [options]\n"); 1.75 + printf("Options:\n"); 1.76 + optcfg_print_options(oc); 1.77 + exit(0); 1.78 + } 1.79 + return 0; 1.80 +}