From 611dcaa4f53bbbc9a2ab44ce69f074efcd54b30e Mon Sep 17 00:00:00 2001 From: Gerard Swiderski Date: Mon, 3 Jul 2023 13:00:46 +0200 Subject: [PATCH] getopt: Add support for :: optional arguments Adds support for getopt extension: option characters followed by two colons. A character followed by a single colon indicates that an argument is to follow the option on the command line. Two colons indicates that the argument is optional (this is transparent extension not covered by POSIX). optsting = "a:bX" In the string above, option a will accept an optional argument. (Option requires an argument) Usage: Option syntax Meaning -a OK, No argument provided (optional). -afoo OK, argument is foo -a foo Wrong, no space allowed with optional arguments. foo is considered a non-option argument. -bfoo OK, argument is foo (required). -b foo OK, argument is foo (required). -b Wrong, option b requires an argument. Since the argument is optional, you will have to check the value of optarg to see if it is a valid pointer (otherwise, it's NULL). JIRA: RTOS-511 --- lib/getopt.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/getopt.c b/lib/getopt.c index 0eb3a770..068ce519 100644 --- a/lib/getopt.c +++ b/lib/getopt.c @@ -84,6 +84,10 @@ int lib_getopt(int argc, char *const argv[], const char *optstring) /* Argument in the same argv */ optarg = &argv[optind][getopt_common.optwhere]; } + else if (*(++optspec) == ':') { + /* Optional argument */ + optarg = NULL; + } else if (optind + 1 < argc) { /* Argument in the next argv */ optarg = argv[optind + 1];