From: Michael D. Lowis Date: Fri, 31 Oct 2014 14:53:20 +0000 (-0400) Subject: Added function for formatting and printing the options list to a filehandle X-Git-Url: https://git.mdlowis.com/?a=commitdiff_plain;h=3d9169274240cb0edd16aea0d374c63c49d86eab;p=projs%2Fopts.git Added function for formatting and printing the options list to a filehandle --- diff --git a/source/opts.c b/source/opts.c index 26e9a63..f4e77d0 100755 --- a/source/opts.c +++ b/source/opts.c @@ -307,4 +307,37 @@ const char** opts_arguments(void) { return ret; } +/*****************************************************************************/ +static int opts_calc_padding(opts_cfg_t* opts) { + bool opts_have_args = false; + size_t sz = 0; + /* Figure out the longest option name */ + while (NULL != opts->name) { + size_t name_sz = strlen(opts->name); + if (name_sz > sz) { + sz = name_sz; + } + if (opts->has_arg) { + opts_have_args = true; + } + opts++; + } + return sz + 4 + ((opts_have_args) ? 4 : 0); +} + +void opts_print_help(FILE* ofile, opts_cfg_t* opts) { + int padding = opts_calc_padding(opts); + char* buffer = (char*)malloc(padding+1); + while (NULL != opts->name) { + if (1 == strlen(opts->name)) + sprintf(buffer, " -%s", opts->name); + else + sprintf(buffer, " --%s", opts->name); + if (opts->has_arg) sprintf(&buffer[strlen(buffer)], "=ARG "); + fprintf(ofile, "%-*s%s\n", padding, buffer, opts->desc); + opts++; + } + free(buffer); + exit(1); +} diff --git a/source/opts.h b/source/opts.h index 7e51bdc..1fdeb6a 100755 --- a/source/opts.h +++ b/source/opts.h @@ -29,6 +29,8 @@ const char** opts_select(const char* name, const char* tag); const char** opts_arguments(void); +void opts_print_help(FILE* ofile, opts_cfg_t* opts); + #ifdef __cplusplus } #endif