Skip to content

Commit

Permalink
getopt: Add support for :: optional arguments
Browse files Browse the repository at this point in the history
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::b:X"

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
  • Loading branch information
gerard5 committed Jul 3, 2023
1 parent 2843950 commit aea9d73
Showing 1 changed file with 4 additions and 0 deletions.
4 changes: 4 additions & 0 deletions unistd/getopt.c
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ int getopt(int argc, char * const argv[], const char *optstring)
/* Argument in the same argv */
optarg = &argv[optind][optwhere];
}
else if (*(++optspec) == ':') {
/* Optional argument */
optarg = NULL;
}
else if (optind + 1 < argc) {
/* Argument in the next argv */
optarg = argv[optind + 1];
Expand Down

0 comments on commit aea9d73

Please sign in to comment.