]> git.mdlowis.com Git - projs/opts.git/commitdiff
Added function for formatting and printing the options list to a filehandle
authorMichael D. Lowis <mike.lowis@gentex.com>
Fri, 31 Oct 2014 14:53:20 +0000 (10:53 -0400)
committerMichael D. Lowis <mike.lowis@gentex.com>
Fri, 31 Oct 2014 14:53:20 +0000 (10:53 -0400)
source/opts.c
source/opts.h

index 26e9a638c1f223d32b9ef761027b93f9c621e69c..f4e77d09c8024dd4d41124df93816a5d36a48bc4 100755 (executable)
@@ -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);
+}
index 7e51bdc3f6928a1f5fa503407e05d3e23010e62d..1fdeb6a81b831a66c25788094454f97f7d31a8e5 100755 (executable)
@@ -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