nuclear@1: #include nuclear@1: #include nuclear@1: #include nuclear@1: nuclear@1: enum { nuclear@1: OPT_FOO, nuclear@1: OPT_BAR, nuclear@1: OPT_XYZZY, nuclear@1: OPT_HELP nuclear@1: }; nuclear@1: nuclear@1: struct optcfg_option options[] = { nuclear@1: /* short, long, id, description */ nuclear@1: {'f', "foo", OPT_FOO, "foo does nothing really"}, nuclear@1: {'b', "bar", OPT_BAR, "bar also does nothing"}, nuclear@1: {0, "xyzzy", OPT_XYZZY, "xyzzy doesn't have a short option"}, nuclear@1: {'h', "help", OPT_HELP, "print usage and exit"}, nuclear@1: {0, 0, -1, 0} /* terminate with id=-1 */ nuclear@1: }; nuclear@1: nuclear@1: int foo, bar; nuclear@1: int xyzzy; nuclear@1: nuclear@1: int opt_handler(struct optcfg *oc, int opt, void *cls); nuclear@1: nuclear@1: int main(int argc, char **argv) nuclear@1: { nuclear@1: /* pass the options array to initialize the optcfg object */ nuclear@1: struct optcfg *oc = optcfg_init(options); nuclear@1: /* set the option callback function */ nuclear@1: optcfg_set_opt_callback(oc, opt_handler, 0); nuclear@1: /* first let's load options from a config file */ nuclear@1: printf("parsing config file: example.conf\n"); nuclear@1: if(optcfg_parse_config_file(oc, "example.conf") == -1) { nuclear@1: return 1; nuclear@1: } nuclear@1: /* then let's override those with commandline options */ nuclear@1: printf("parsing commandline arguments\n"); nuclear@1: if(optcfg_parse_args(oc, argc, argv) == -1) { nuclear@1: return 1; nuclear@1: } nuclear@1: nuclear@1: printf("\nfoo: %s\n", foo ? "true" : "false"); nuclear@1: printf("bar: %s\n", bar ? "true" : "false"); nuclear@1: printf("xyzzy: %d\n", xyzzy); nuclear@1: nuclear@1: optcfg_destroy(oc); nuclear@1: return 0; nuclear@1: } nuclear@1: nuclear@1: int opt_handler(struct optcfg *oc, int opt, void *cls) nuclear@1: { nuclear@1: char *val; nuclear@1: nuclear@1: switch(opt) { nuclear@1: case OPT_FOO: nuclear@2: optcfg_enabled_value(oc, &foo); nuclear@1: break; nuclear@1: case OPT_BAR: nuclear@2: optcfg_enabled_value(oc, &bar); nuclear@1: break; nuclear@1: case OPT_XYZZY: nuclear@1: /* this option needs an integer value */ nuclear@1: if(!(val = optcfg_next_value(oc)) || optcfg_int_value(val, &xyzzy) == -1) { nuclear@1: fprintf(stderr, "xyzzy must be followed by a number\n"); nuclear@1: return -1; nuclear@1: } nuclear@1: break; nuclear@1: case OPT_HELP: nuclear@1: /* print usage and exit */ nuclear@1: printf("Usage: example [options]\n"); nuclear@1: printf("Options:\n"); nuclear@1: optcfg_print_options(oc); nuclear@1: exit(0); nuclear@1: } nuclear@1: return 0; nuclear@1: }