From 4a59fd131229968b08af9bdf221c341f54c52983 Mon Sep 17 00:00:00 2001 From: Pierre Habouzit Date: Mon, 15 Oct 2007 01:35:37 +0200 Subject: Add a simple option parser. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The option parser takes argc, argv, an array of struct option and a usage string. Each of the struct option elements in the array describes a valid option, its type and a pointer to the location where the value is written. The entry point is parse_options(), which scans through the given argv, and matches each option there against the list of valid options. During the scan, argv is rewritten to only contain the non-option command line arguments and the number of these is returned. Aggregation of single switches is allowed: -rC0 is the same as -r -C 0 (supposing that -C wants an arg). Every long option automatically support the option with the same name, prefixed with 'no-' to unset the switch. It assumes that initial value for strings are "NULL" and for integers is "0". Long options are supported either with '=' or without: --some-option=foo is the same as --some-option foo Acked-by: Kristian Høgsberg Signed-off-by: Pierre Habouzit Signed-off-by: Shawn O. Pearce --- parse-options.h | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 parse-options.h (limited to 'parse-options.h') diff --git a/parse-options.h b/parse-options.h new file mode 100644 index 0000000000..76d73b299f --- /dev/null +++ b/parse-options.h @@ -0,0 +1,35 @@ +#ifndef PARSE_OPTIONS_H +#define PARSE_OPTIONS_H + +enum parse_opt_type { + OPTION_END, + OPTION_BOOLEAN, + OPTION_STRING, + OPTION_INTEGER, +}; + +enum parse_opt_flags { + PARSE_OPT_KEEP_DASHDASH = 1, +}; + +struct option { + enum parse_opt_type type; + int short_name; + const char *long_name; + void *value; +}; + +#define OPT_END() { OPTION_END } +#define OPT_BOOLEAN(s, l, v, h) { OPTION_BOOLEAN, (s), (l), (v) } +#define OPT_INTEGER(s, l, v, h) { OPTION_INTEGER, (s), (l), (v) } +#define OPT_STRING(s, l, v, a, h) { OPTION_STRING, (s), (l), (v) } + +/* parse_options() will filter out the processed options and leave the + * non-option argments in argv[]. + * Returns the number of arguments left in argv[]. + */ +extern int parse_options(int argc, const char **argv, + const struct option *options, + const char *usagestr, int flags); + +#endif -- cgit v1.2.1