Museum

Home

Lab Overview

Retrotechnology Articles

⇒ Online Manual

Media Vault

Software Library

Restoration Projects

Artifacts Sought

Related Articles

getopt(1)

GETOPT(3C)

NAME

getopt, optarg, optind, opterr − get option letter from argument vector

SYNOPSIS

int getopt (argc, argv, optstring)
int argc;
char ∗∗argv, ∗opstring;

extern char ∗optarg;
extern int optind, opterr;

HP-UX COMPATIBILITY

Level: HP-UX/RUN ONLY

Origin: System V

DESCRIPTION

Getopt returns the next option letter in argv (starting from argv[1]) that matches a letter in optstring. Optstring is a string of recognized option letters; if a letter is followed by a colon, the option is expected to have an argument that may or may not be separated from it by white space.  Optarg is set to point to the start of the option argument on return from getopt.

Getopt places in optind the argv index of the next argument to be processed.  Because optind is external, it is normally initialized to zero automatically before the first call to getopt.

When all options have been processed (i.e., up to the first non-option argument), getopt returns EOF.  The special option −− may be used to delimit the end of the options; EOF will be returned, and −− will be skipped. 

DIAGNOSTICS

Getopt prints an error message on stderr and returns a question mark (?) when it encounters an option letter not included in optstring. This error message may be disabled by setting opterr to zero. 

WARNING

The above routine uses <stdio.h>, which causes it to increase the size of programs, not otherwise using standard I/O, more than might be expected. 

Options can be any ASCII characters except colon (:), question mark (?), or null (\0).  It is impossible to distinguish between a ? used as a legal option, and the character that getopt returns when it encounters an invalid option character in the input. 

EXAMPLE

The following code fragment shows how one might process the arguments for a command that can take the mutually exclusive options a and b, and the options f and o, both of which require arguments:

main (argc, argv)
int argc;
char ∗∗argv;
{
int c;
extern char ∗optarg;
extern int optind;
.
.
.
while ((c = getopt(argc, argv, "abf:o:")) != EOF)
switch (c) {
case ’a’:
if (bflg)
errflg++;
else
aflg++;
break;
case ’b’:
if (aflg)
errflg++;
else
bproc( );
break;
case ’f’:
ifile = optarg;
break;
case ’o’:
ofile = optarg;
break;
case ’?’:
errflg++;
}
if (errflg) {
fprintf(stderr, "usage: . . . ");
exit (2);
}
for ( ; optind < argc; optind++) {
if (access(argv[optind], 4)) {
.
.
.
}

SEE ALSO

getopt(1). 

Hewlett-Packard  —  last mod. May 11, 2021

Typewritten Software • bear@typewritten.org • Edmonds, WA 98026