xref: /netbsd-src/lib/libc/stdlib/getopt_long.3 (revision e4d7c2e329d54c97e0c0bd3016bbe74f550c3d5e)
1.\"	$NetBSD: getopt_long.3,v 1.1 1999/07/23 03:55:27 mcr Exp $
2.\"
3.\" Copyright (c) 1988, 1991, 1993
4.\"	The Regents of the University of California.  All rights reserved.
5.\"
6.\" Redistribution and use in source and binary forms, with or without
7.\" modification, are permitted provided that the following conditions
8.\" are met:
9.\" 1. Redistributions of source code must retain the above copyright
10.\"    notice, this list of conditions and the following disclaimer.
11.\" 2. Redistributions in binary form must reproduce the above copyright
12.\"    notice, this list of conditions and the following disclaimer in the
13.\"    documentation and/or other materials provided with the distribution.
14.\" 3. All advertising materials mentioning features or use of this software
15.\"    must display the following acknowledgement:
16.\"	This product includes software developed by the University of
17.\"	California, Berkeley and its contributors.
18.\" 4. Neither the name of the University nor the names of its contributors
19.\"    may be used to endorse or promote products derived from this software
20.\"    without specific prior written permission.
21.\"
22.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32.\" SUCH DAMAGE.
33.\"
34.\"     @(#)getopt.3	8.5 (Berkeley) 4/27/95
35.\"
36.Dd November 19, 1998
37.Dt GETOPT_LONG 3
38.Os NetBSD 4.4
39.Sh NAME
40.Nm getopt_long
41.Nd get long options from command line argument list
42.Sh LIBRARY
43.Lb libc
44.Sh SYNOPSIS
45.Fd #include <unistd.h>
46.Fd #include <getopt.h>
47.Vt struct option {
48.Vt	char *	name;
49.Vt	int  has_arg;
50.Vt	int * flag;
51.Vt	int val;
52.Vt };
53.Vt extern char *optarg;
54.Vt extern int   optind;
55.Vt extern int   optopt;
56.Vt extern int   opterr;
57.Vt extern int   optreset;
58.Ft int
59.Fn getopt "int argc" "char * const *argv" "const char *optstring"
60.Ft int
61.Fn getopt_long "int argc" "char * const *argv" "const char *optstring"
62"struct options *long options" "int *index"
63.Sh DESCRIPTION
64The
65.Fn getopt
66function incrementally parses a command line argument list
67.Fa argv
68and returns the next
69.Em known
70option character.
71An option character is
72.Em known
73if it has been specified in the string of accepted option characters,
74.Fa optstring .
75.Pp
76The
77.Fn getopt_long
78function is similar to
79.Fn getopt
80but it accepts options in two forms: words and characters. The
81.Fn getopt_long
82function provides a superset of of the functionality of
83.Fn getopt
84The additional functionality is described in the section GETOPT_LONG.
85.Pp
86The option string
87.Fa optstring
88may contain the following elements: individual characters, and
89characters followed by a colon to indicate an option argument
90is to follow.
91For example, an option string
92.Li "\&""x""
93recognizes an option
94.Dq Fl x ,
95and an option string
96.Li "\&""x:""
97recognizes an option and argument
98.Dq Fl x Ar argument .
99It does not matter to
100.Fn getopt
101if a following argument has leading white space.
102.Pp
103On return from
104.Fn getopt ,
105.Va optarg
106points to an option argument, if it is anticipated,
107and the variable
108.Va optind
109contains the index to the next
110.Fa argv
111argument for a subsequent call
112to
113.Fn getopt .
114The variable
115.Va optopt
116saves the last
117.Em known
118option character returned by
119.Fn getopt .
120.Pp
121The variable
122.Va opterr
123and
124.Va optind
125are both initialized to 1.
126The
127.Va optind
128variable may be set to another value before a set of calls to
129.Fn getopt
130in order to skip over more or less argv entries.
131.Pp
132In order to use
133.Fn getopt
134to evaluate multiple sets of arguments, or to evaluate a single set of
135arguments multiple times,
136the variable
137.Va optreset
138must be set to 1 before the second and each additional set of calls to
139.Fn getopt ,
140and the variable
141.Va optind
142must be reinitialized.
143.Pp
144The
145.Fn getopt
146function
147returns \-1
148when the argument list is exhausted, or a non-recognized
149option is encountered.
150The interpretation of options in the argument list may be cancelled
151by the option
152.Ql --
153(double dash) which causes
154.Fn getopt
155to signal the end of argument processing and returns \-1.
156When all options have been processed (i.e., up to the first non-option
157argument),
158.Fn getopt
159returns \-1.
160.Sh GETOPT_LONG
161.Pp
162.Fn getopt_long
163can be used in two ways. In the first way, every long option understood
164by the program has a coresponding short option, and the option
165structure is only used to translate from long option to short
166options. When used in this fashion,
167.Fn getopt_long
168behaves identically to
169.Fn getopt.
170This is good way to add long option processing to an existing program
171with the minimum of rewriting.
172.Pp
173In the second mechanism, a long option set a flag in the
174.Fa option
175structure passed, or will store a pointer to the command line argument
176in the
177.Fa option
178structure passed to it for options that take arguments. Additionally,
179the long option's argument may be specified as a single argument with
180an equal sign, e.g
181.Bd -literal
182myprogram --myoption=somevalue
183.Ed
184.Pp
185When a long option is processed the call to
186.Fn getopt_long
187will return 0. For this reason, long option processing without
188shortcuts are not backwards compatible with
189.Fn getopt.
190.Pp
191It is possible to combine these methods, providing for long options
192processing with short option equivalents for some options. Less
193frequently used options would be processed as long options only.
194.Sh USAGE OF GETOPT_LONG
195.Pp
196The
197.Fn getopt_long
198call requires a structure to be initialized describing the long
199options. The structure is:
200.Bd -literal
201struct option {
202    char *	name;
203    int  has_arg;
204    int * flag;
205    int val;
206};
207.Ed
208.Pp
209The
210.Fa name
211field should contain the option name without the leading double dash.
212.Pp
213The
214.Fa has_arg
215field should be one of
216.Bl -tag
217.It no_argument
218no argument to the option is expect.
219.It required_argument
220an argument to the option is required.
221.It optional_argument
222an argument to the option may be presented.
223.El
224.Pp
225If
226.Fa flag
227is non-NULL, then the integer pointed to by it will set to the value
228in the
229.Fa val
230field. If the
231.Fa flag
232field is NULL, then the
233.Fa val
234field will be returned. Setting
235.Fa flag
236to NULL and setting
237.Fa val
238to the corresponding short option will make this function act just
239like
240.Fa getopt.
241.Sh DIAGNOSTICS
242If the
243.Fn getopt
244function encounters a character not found in the string
245.Fa optstring
246or detects
247a missing option argument it writes an error message to
248.Va stderr
249and returns
250.Ql ? .
251Setting
252.Va opterr
253to a zero will disable these error messages.
254If
255.Va optstring
256has a leading
257.Ql \&:
258then a missing option argument causes a
259.Ql \&:
260to be returned in addition to suppressing any error messages.
261.Pp
262Option arguments are allowed to begin with
263.Dq Li \- ;
264this is reasonable but
265reduces the amount of error checking possible.
266.Sh GETOPT_LONG
267.Sh EXTENSIONS
268The
269.Va optreset
270variable was added to make it possible to call the
271.Fn getopt
272function multiple times.
273This is an extension to the
274.St -p1003.2
275specification.
276.Sh EXAMPLE
277.Bd -literal -compact
278extern char *optarg;
279extern int optind;
280int bflag, ch, fd;
281
282bflag = 0;
283while ((ch = getopt(argc, argv, "bf:")) != -1)
284	switch(ch) {
285	case 'b':
286		bflag = 1;
287		break;
288	case 'f':
289		if ((fd = open(optarg, O_RDONLY, 0)) < 0) {
290			(void)fprintf(stderr,
291			    "myname: %s: %s\en", optarg, strerror(errno));
292			exit(1);
293		}
294		break;
295	case '?':
296	default:
297		usage();
298}
299argc -= optind;
300argv += optind;
301.Ed
302.Sh LONG EXAMPLE
303.Bd -literal -compact
304extern char *optarg;
305extern int optind;
306int bflag, ch, fd;
307int daggerset;
308
309/* options descriptor */
310static struct option longopts[] =
311{
312  {"buffy",       no_argument,       0, 'b'},
313  {"floride",     required_argument, 0, 'f'},
314  {"daggerset",   no_argument, &daggerset, 1},
315  {0, 		   0,                0, 0}
316};
317
318bflag = 0;
319while ((ch = getopt_long(argc, argv, "bf:")) != -1)
320	switch(ch) {
321	case 'b':
322		bflag = 1;
323		break;
324	case 'f':
325		if ((fd = open(optarg, O_RDONLY, 0)) < 0) {
326			(void)fprintf(stderr,
327			    "myname: %s: %s\en", optarg, strerror(errno));
328			exit(1);
329		}
330		break;
331	case 0:
332		if(daggerset) {
333			fprintf(stderr,"Buffy will put use her dagger"
334				       "to apply floride to dracula's teeth");
335		}
336		break;
337	case '?':
338	default:
339		usage();
340}
341argc -= optind;
342argv += optind;
343.Ed
344.Sh HISTORY
345The
346.Fn getopt
347function appeared
348.Bx 4.3 .
349The
350.Fn getopt_long
351function first appeared in GNU libiberty. This implementation was
352imported to NetBSD from a Kerberos distribution.
353.Sh BUGS
354The
355.Fn getopt
356function was once specified to return
357.Dv EOF
358instead of \-1.
359This was changed by
360.St -p1003.2-92
361to decouple
362.Fn getopt
363from
364.Pa <stdio.h> .
365.Pp
366A single dash
367.Dq Li -
368may be specified as an character in
369.Fa optstring ,
370however it should
371.Em never
372have an argument associated with it.
373This allows
374.Fn getopt
375to be used with programs that expect
376.Dq Li -
377as an option flag.
378This practice is wrong, and should not be used in any current development.
379It is provided for backward compatibility
380.Em only .
381By default, a single dash causes
382.Fn getopt
383to return \-1.
384This is, we believe, compatible with System V.
385.Pp
386It is also possible to handle digits as option letters.
387This allows
388.Fn getopt
389to be used with programs that expect a number
390.Pq Dq Li \&-\&3
391as an option.
392This practice is wrong, and should not be used in any current development.
393It is provided for backward compatibility
394.Em only .
395The following code fragment works in most cases.
396.Bd -literal -offset indent
397int length;
398char *p;
399
400while ((c = getopt(argc, argv, "0123456789")) != -1)
401	switch (c) {
402	case '0': case '1': case '2': case '3': case '4':
403	case '5': case '6': case '7': case '8': case '9':
404		p = argv[optind - 1];
405		if (p[0] == '-' && p[1] == ch && !p[2])
406			length = atoi(++p);
407		else
408			length = atoi(argv[optind] + 1);
409		break;
410	}
411}
412.Ed
413.Pp
414The
415.Fa optional_argument
416always eats the following argument unless the argument is included via
417the
418.Em --option=argument
419notation.
420