Tried to improve getopt()
Gregory Pietsch
gpietsch@comcast.net
Thu Aug 30 21:08:00 GMT 2012
Here's my latest patch, correcting what Eric Blake said were mistakes.
Also, I did this with the -abuZ options of diff, so you might want to
run the resulting file through indent before reposting it:
--- getopt.c.old 2012-08-26 19:24:27.466130300 -0400
+++ getopt.c 2012-08-27 11:21:00.777353500 -0400
@@ -71,6 +71,14 @@
value of ordering. In the case of RETURN_IN_ORDER, only `--' can cause
getopt() and friends to return EOF with optind != argc.
+2012-08-26: Tried to make the error handling more sus4-like. The functions
+return a colon if getopt() and friends detect a missing argument and the
+first character of shortopts/optstring starts with a colon (`:'). If
getopt()
+and friends detect a missing argument and shortopts/optstring does not
start
+with a colon, the function returns a question mark (`?'). If it was a
missing
+argument to a short option, optopt is set to the character in question. The
+colon goes after the ordering character (`+' or `-').
+
COPYRIGHT NOTICE AND DISCLAIMER:
Copyright (C) 1997 Gregory Pietsch
@@ -185,6 +193,7 @@
int has_arg = -1;
char *cp = 0;
int arg_next = 0;
+ int initial_colon = 0;
/* first, deal with silly parameters and easy stuff */
if (argc == 0 || argv == 0 || (shortopts == 0 && longopts == 0)
@@ -209,6 +218,13 @@
else
ordering = (getenv ("POSIXLY_CORRECT") != 0) ? REQUIRE_ORDER :
PERMUTE;
+ /* check for initial colon in shortopts */
+ if (shortopts != 0 && *shortopts == ':')
+ {
+ ++shortopts;
+ initial_colon = 1;
+ }
+
/*
* based on ordering, find our next option, if we're at the beginning of
* one
@@ -359,12 +375,18 @@
{
fprintf (stderr, "%s: argument required for option `", argv[0]);
if (longopt_match >= 0)
+ {
fprintf (stderr, "--%s'\n", longopts[longopt_match].name);
+ data->optopt = initial_colon ? ':' : '\?';
+ }
else
+ {
fprintf (stderr, "-%c'\n", *cp);
+ data->optopt = *cp;
+ }
}
data->optind++;
- return (data->optopt = ':');
+ return initial_colon ? ':' : '\?';
}
else
{
More information about the Newlib
mailing list