(Slightly different from UNIX function)
extern char *optarg; extern int optind, opterr; int getopt(); c = getopt(argc,argv,legalopts);
The "getopt" function is designed to parse UNIX-style command lines. It is not particularly suited to any other command line format.
Options are presumed to have one of the following forms.
X Xargument XXX... -X -Xargument -XXX... +X +Xargument +XXX...
where 'X' can be any character other than '-', '+', or ':'. In traditional UNIX environments, 'X' is assumed to be an upper or lower case letter.
Accepted values for 'X' are given in the string "legalopts". Option formats that take an argument (e.g. -Xargument) are indicated by a colon ':' following the option character in the "legalopts" string. For example, suppose the following option formats are valid.
-A +a -a -Pfilename
Then the "legalopts" string for "getopt" would be "AaP:". This would also let you concatenate options as in "-Aa".
"getopt" will scan the string "argv[optind]" for the first non-blank character that is not '-' or '+'. If this matches one of the characters in "legalopts", "getopt" returns the character it finds. If the matching character in "legalopts" was followed by a colon, "getopt" also sets "optarg" to point at the string that follows the option character.
An error message is normally issued if the first character found does not appear in "legalopts" or if the character is supposed to be followed by an argument but isn't. In these cases, "getopt" returns the '?' character. The error messages can be suppressed by assigning "opterr" a non-zero value.
Concatenated options are recognized. For example, if you have "-ab" as a string in "argv", the first call to "getopt" could return 'a' and the second could return 'b'.
"getopt" returns the EOF character when it reaches the end of the strings in "argv". It also returns EOF if it encounters the string "--" in any of the "argv" strings. Thus you can use "--" if you don't want the rest of a command line scanned. This gives you a crude commenting ability when calling the program, as in
command -options -- Comment here
The variables "optarg", "optind", and "opterr" are all static storage areas. Because of this, "getopt" cannot be used in re-entrant code (e.g. signal handlers). Each call to "getopt" may overwrite the previous values stored in "optind" and "*optarg".
The use of "+" to mark options (as in "+X") is unique to C compilers maintained by Thinkage Ltd. Thus "+" options should be avoided in programs that may be ported to other systems.
Copyright © 1996, Thinkage Ltd.