liboptcfg
view example/example.c @ 3:f971dfa66076
foo
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Wed, 27 Jul 2016 04:31:40 +0300 |
parents | 9c73004c7af3 |
children |
line source
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <optcfg.h>
5 enum {
6 OPT_FOO,
7 OPT_BAR,
8 OPT_XYZZY,
9 OPT_HELP
10 };
12 struct optcfg_option options[] = {
13 /* short, long, id, description */
14 {'f', "foo", OPT_FOO, "foo does nothing really"},
15 {'b', "bar", OPT_BAR, "bar also does nothing"},
16 {0, "xyzzy", OPT_XYZZY, "xyzzy doesn't have a short option"},
17 {'h', "help", OPT_HELP, "print usage and exit"},
18 OPTCFG_OPTIONS_END
19 };
21 int foo, bar;
22 int xyzzy;
24 int opt_handler(struct optcfg *oc, int opt, void *cls);
26 int main(int argc, char **argv)
27 {
28 /* pass the options array to initialize the optcfg object */
29 struct optcfg *oc = optcfg_init(options);
30 /* set the option callback function */
31 optcfg_set_opt_callback(oc, opt_handler, 0);
32 /* first let's load options from a config file */
33 printf("parsing config file: example.conf\n");
34 if(optcfg_parse_config_file(oc, "example.conf") == -1) {
35 return 1;
36 }
37 /* then let's override those with commandline options */
38 printf("parsing commandline arguments\n");
39 if(optcfg_parse_args(oc, argc, argv) == -1) {
40 return 1;
41 }
43 printf("\nfoo: %s\n", foo ? "true" : "false");
44 printf("bar: %s\n", bar ? "true" : "false");
45 printf("xyzzy: %d\n", xyzzy);
47 optcfg_destroy(oc);
48 return 0;
49 }
51 int opt_handler(struct optcfg *oc, int opt, void *cls)
52 {
53 char *val;
55 switch(opt) {
56 case OPT_FOO:
57 optcfg_enabled_value(oc, &foo);
58 break;
59 case OPT_BAR:
60 optcfg_enabled_value(oc, &bar);
61 break;
62 case OPT_XYZZY:
63 /* this option needs an integer value */
64 if(!(val = optcfg_next_value(oc)) || optcfg_int_value(val, &xyzzy) == -1) {
65 fprintf(stderr, "xyzzy must be followed by a number\n");
66 return -1;
67 }
68 break;
69 case OPT_HELP:
70 /* print usage and exit */
71 printf("Usage: example [options]\n");
72 printf("Options:\n");
73 optcfg_print_options(oc);
74 exit(0);
75 }
76 return 0;
77 }