5da0c1f72cd1f5a8a1a99e8490b03c6a94104678
[external/popt.git] / popt.3
1 .TH POPT 3  "June 30, 1998" "" "Linux Programmer's Manual"
2 .SH NAME
3 popt \- Parse command line options
4 .SH SYNOPSIS
5 .nf
6 .B #include <popt.h>
7 .sp
8 .BI "poptContext poptGetContext(const char * " name ", int " argc ,
9 .BI "                           const char ** "argv ,
10 .BI "                           const struct poptOption * " options ,
11 .BI "                           int " flags );
12 .sp
13 .BI "void poptFreeContext(poptContext " con );
14 .sp
15 .BI "void poptResetContext(poptContext " con );
16 .sp
17 .BI "int poptGetNextOpt(poptContext " con );
18 .sp
19 .BI "const char * poptGetOptArg(poptContext " con );
20 .sp
21 .BI "const char * poptGetArg(poptContext " con );
22 .sp
23 .BI "const char * poptPeekArg(poptContext " con );
24 .sp
25 .BI "const char ** poptGetArgs(poptContext " con );
26 .sp
27 .BI "const char *const poptStrerror(const int " error );
28 .sp
29 .BI "const char * poptBadOption(poptContext " con ", int " flags );
30 .sp
31 .BI "int poptReadDefaultConfig(poptContext " con ", int " flags );
32 .sp
33 .BI "int poptReadConfigFile(poptContext " con ", char * " fn );
34 .sp
35 .BI "int poptAddAlias(poptContext " con ", struct poptAlias " alias , 
36 .BI "                 int " flags );
37 .sp
38 .BI "int poptParseArgvString(char * " s ", int *  " argcPtr , 
39 .BI "                        const char *** " argvPtr );
40 .sp
41 .BI "int poptDupArgv(int " argc ", const char ** " argv ", int * " argcPtr ",
42 .BI "                        const char *** " argvPtr ");"
43 .sp
44 .BI "int poptStuffArgs(poptContext " con ", const char ** " argv );
45 .sp
46 .fi
47 .SH DESCRIPTION
48 The popt library exists essentially for parsing command-line 
49 options. It is found superior in many ways when compared to 
50 parsing the argv array by hand or using the getopt functions 
51 .B getopt()
52 and 
53 .B getopt_long()
54 [see 
55 .BR getopt "(3)]."  
56 Some specific advantages of popt are: it does not utilize global 
57 .RI "variables, thus enabling multiple passes in parsing " argv
58 .RI "; it can parse an arbitrary array of " argv "-style elements, "
59 allowing parsing of command-line-strings from any source; 
60 it provides a standard method of option aliasing (to be 
61 discussed at length below.); it can exec external option filters; and,
62 finally, it can automatically generate help and usage messages for
63 the application.
64 .sp
65 Like
66 .BR getopt_long() ,
67 the popt library supports short and long style options.  Recall 
68 that a 
69 .B short option
70 consists of a - character followed by a single alphanumeric character.
71
72 .BR "long option" ,
73 common in GNU utilities, consists of two - characters followed by a
74 string made up of letters, numbers and hyphens.  Long options are
75 optionally allowed to begin with a single -, primarily to allow command-line
76 compatibility between popt applications and X toolkit applications.
77 Either type of option may be followed by an argument.  A space separates a 
78 short option from its arguments; either a space or an = separates a long 
79 option from an argument. 
80 .sp
81 The popt library is highly portable and should work on any POSIX 
82 platform.  The latest version is distributed with rpm and is always available
83 from: ftp://ftp.rpm.org/pub/rpm/dist.
84 .sp
85 It may be redistributed under the X consortium license, see the file COPYING
86 in the popt source distribution for details.
87 .SH "BASIC POPT USAGE"
88 .SS "1. THE OPTION TABLE"
89 Applications provide popt with information on their command-line 
90 options by means of an "option table," i.e., an array of 
91 .B struct poptOption 
92 structures:
93 .sp
94 #include <popt.h>
95 .sp
96 .nf
97 struct poptOption {
98     const char * longName; /* may be NULL */
99     char shortName;        /* may be '\\0' */
100     int argInfo;
101     void * arg;            /* depends on argInfo */
102     int val;               /* 0 means don't return, just update flag */
103     char * descrip;        /* description for autohelp -- may be NULL */
104     char * argDescrip;     /* argument description for autohelp */
105 };
106 .fi
107 .sp
108 Each member of the table defines a single option that may be 
109 passed to the program.  Long and short options are considered 
110 a single option that may occur in two different forms.  The 
111 first two members, 
112 .IR longName " and " shortName ", define the names of the option;"
113 the first is a long name, while the latter is a single character.
114 .sp
115 The 
116 .IR argInfo " member tells popt what type of argument is expected" 
117 after the argument.  If no option is expected,
118 .B POPT_ARG_NONE
119 should be used.
120 The rest of the valid values are shown in the following table:
121 .sp
122 .TS
123 lfB lfB lfB
124 lfB lfR lfR.
125 Value   Description     arg Type
126 POPT_ARG_NONE   No argument expected    int
127 POPT_ARG_STRING No type checking to be performed        char *
128 POPT_ARG_INT    An integer argument is expected int
129 POPT_ARG_LONG   A long integer is expected      long
130 POPT_ARG_VAL    Integer value taken from \f(CWval\fR    int
131 POPT_ARG_FLOAT  An float argument is expected   float
132 POPT_ARG_DOUBLE A double argument is expected   double
133 .TE
134 .sp
135 For numeric values, if the \fIargInfo\fR value is bitwise or'd with one of
136 \fBPOPT_ARGFLAG_OR\fR, \fBPOPT_ARGFLAG_AND\fR, or \fBPOPT_ARGFLAG_XOR\fR,
137 the value is saved by performing an OR, AND, or XOR.
138 If the \fIargInfo\fR value is bitwise or'd with \fBPOPT_ARGFLAG_NOT\fR,
139 the value will be negated before saving. For the common operations of
140 setting and/or clearing bits, \fBPOPT_BIT_SET\fR and \fBPOPT_BIT_CLR\fR
141 have the appropriate flags set to perform bit operations.
142 .sp
143 If the \fIargInfo\fR value is bitwise or'd with \fBPOPT_ARGFLAG_ONEDASH\fR,
144 the long argument may be given with a single - instead of two. For example,
145 if \fB--longopt\fR is an option with \fBPOPT_ARGFLAG_ONEDASH\fR, is
146 specified, \fB-longopt\fR is accepted as well.
147 .sp
148 .RI "The next element, " arg ", allows popt to automatically update "
149 .RI "program variables when the option is used. If " arg " is " 
150 .BR NULL ", it is ignored and popt takes no special action. " 
151 Otherwise it should point to a variable of the type indicated in the 
152 right-most column of the table above.
153 .sp
154 .RI "If the option takes no argument (" argInfo " is " 
155 .BR POPT_ARG_NONE "), the variable pointed to by " 
156 .IR arg " is set to 1 when the option is used.  (Incidentally, it "
157 will perhaps not escape the attention of hunt-and-peck typists that 
158 .RB "the value of " POPT_ARG_NONE " is 0.)  If the option does take "
159 an argument, the variable that 
160 .IR arg " points to is updated to reflect the value of the argument." 
161 .RB "Any string is acceptable for " POPT_ARG_STRING " arguments, but "
162 .BR POPT_ARG_INT ", " POPT_ARG_LONG ", " POPT_ARG_FLOAT ", and "
163 .BR POPT_ARG_DOUBLE " are converted to the appropriate type, and an "
164 error returned if the conversion fails.
165 .sp
166 \fBPOPT_ARG_VAL\fR causes \fIarg\fP to be set to the (integer) value of
167 \fIval\fP when the argument is found.  This is most often useful for
168 mutually-exclusive arguments in cases where it is not an error for
169 multiple arguments to occur and where you want the last argument
170 specified to win; for example, "rm -i -f".  \fBPOPT_ARG_VAL\fP causes
171 the parsing function not to return a value, since the value of \fIval\fP
172 has already been used.
173 .sp
174 If the \fIargInfo\fR value is bitwise or'd with \fBPOPT_ARGFLAG_OPTIONAL\fR,
175 the argument to the long option may be omitted. If the long option
176 is used without an argument, a default value of zero or NULL will be saved
177 (if the arg pointer is present), otherwise behavior will be identical to
178 a long option with argument.
179 .sp
180 .RI "The next option, " val ", is the value popt's parsing function 
181 should return when the option is encountered.  If it is 0, the parsing
182 function does not return a value, instead parsing the next 
183 command-line argument.
184 .sp
185 .RI "The last two options, " descrip " and " argDescrip " are only required
186 if automatic help messages are desired (automatic usage messages can
187 .RI "be generated without them). " descrip " is a text description of the
188 .RI "argument and " argdescrip " is a short summary of the type of arguments
189 .RI "the option expects, or NULL if the option doesn't require any 
190 arguments.
191 .sp
192 .RB "If popt should automatically provide " --usage " and " --help " (" -? ")
193 .RB "options, one line in the table should be the macro " POPT_AUTOHELP ".
194 .RB "This macro includes another option table (via " POPT_ARG_INCLUDE_TABLE;
195 see below) in the main one which provides the table entries for these
196 .RB "arguments. When " --usage " or " --help " are passed to programs which
197 use popt's automatical help, popt displays the appropriate message on 
198 stderr as soon as it finds the option, and exits the program with a
199 return code of 0. If you want to use popt's automatic help generation in
200 a different way, you need to explicitly add the option entries to your programs 
201 .RB "option table instead of using " POPT_AUTOHELP ".
202 .sp
203 If the \fIargInfo\fR value is bitwise or'd with \fBPOPT_ARGFLAG_DOC_HIDDEN\fR,
204 the argument will not be shown in help output.
205 .sp
206 If the \fIargInfo\fR value is bitwise or'd with \fBPOPT_ARGFLAG_SHOW_DEFAULT\fR,
207 the inital value of the arg will be shown in help output.
208 .sp
209 The final structure in the table should have all the pointer values set
210 .RB "to " NULL " and all the arithmetic values set to 0, marking the "
211 .RB "end of the table. The macro " POPT_TABLEEND " is provided to do that.
212 .sp
213 There are two types of option table entries which do not specify command
214 line options. When either of these types of entries are used, the
215 \fIlongName\fR element must be \fBNULL\fR and the \fBshortName\fR element
216 must be \fB'\\0'\fR.
217 .sp
218 The first of these special entry types allows the application to nest
219 another option table in the current one; such nesting may extend quite
220 deeply (the actual depth is limited by the program's stack). Including
221 other option tables allows a library to provide a standard set of
222 command-line options to every program which uses it (this is often done
223 in graphical programming toolkits, for example). To do this, set
224 the \fIargInfo\fR field to \fBPOPT_ARG_INCLUDE_TABLE\fR and the
225 \fRarg\fR field to point to the table which is being included. If
226 automatic help generation is being used, the \fIdescrip\fR field should
227 contain a overall description of the option table being included.
228 .sp
229 The other special option table entry type tells popt to call a function (a
230 callback) when any option in that table is found. This is especially usefull
231 when included option tables are being used, as the program which provides
232 the top-level option table doesn't need to be aware of the other options
233 which are provided by the included table. When a callback is set for
234 a table, the parsing function never returns information on an option in
235 the table. Instead, options information must be retained via the callback
236 or by having popt set a variable through the option's \fIarg\fR field.
237 Option callbacks should match the following prototype:
238 .sp
239 .nf
240 .BI "void poptCallbackType(poptContext con, 
241 .BI "                      const struct poptOption * opt, 
242 .BI "                      const char * arg, void * data);
243 .fi
244 .sp
245 The first parameter is the context which is being parsed (see the next
246 section for information on contexts), \fIopt\fR points to the option
247 which triggered this callback, and \fIarg\fR is the option's argument.
248 If the option does not take an argument, \fIarg\fR is \fBNULL\fR.  The
249 final parameter, \fIdata\fR is taken from the \fIdescrip\fR field
250 of the option table entry which defined the callback. As \fIdescrip\fR
251 is a pointer, this allows callback functions to be passed an arbitrary
252 set of data (though a typecast will have to be used).
253 .sp
254 The option table entry which defines a callback has an \fIargInfo\fR of
255 \fBPOPT_ARG_CALLBACK\fR, an \fIarg\fR which points to the callback
256 function, and a \fIdescrip\fR field which specifies an arbitrary pointer
257 to be passed to the callback.
258 .SS "2. CREATING A CONTEXT"
259 popt can interleave the parsing of multiple command-line sets. It allows
260 this by keeping all the state information for a particular set of
261 command-line arguments in a 
262 .BR poptContext " data structure, an opaque type that should not be "
263 modified outside the popt library.
264 .sp
265 .RB "New popt contexts are created by " poptGetContext() ":"
266 .sp
267 .nf
268 .BI "poptContext poptGetContext(const char * " name ", int "argc ",
269 .BI "                           const char ** "argv ",
270 .BI "                           const struct poptOption * "options ",
271 .BI "                           int "flags ");"
272 .fi
273 .sp
274 The first parameter, 
275 .IR name ", is used only for alias handling (discussed later). It "
276 should be the name of the application whose options are being parsed,
277 .RB "or should be " NULL " if no option aliasing is desired. The next "
278 two arguments specify the command-line arguments to parse. These are 
279 .RB "generally passed to " poptGetContext() " exactly as they were "
280 .RB "passed to the program's " main() " function. The " 
281 .IR options " parameter points to the table of command-line options, "
282 which was described in the previous section. The final parameter, 
283 .IR flags ,
284 can take one of three values:
285 .br
286 .TS
287 lfB lfB
288 lfB lfR.
289 Value   Description
290 POPT_CONTEXT_NO_EXEC    Ignore exec expansions
291 POPT_CONTEXT_KEEP_FIRST Do not ignore argv[0]
292 POPT_CONTEXT_POSIXMEHARDER      Options cannot follow arguments
293 .TE
294 .sp
295 .RB "A " poptContext " keeps track of which options have already been "
296 parsed and which remain, among other things. If a program wishes to 
297 restart option processing of a set of arguments, it can reset the 
298 .BR poptContext " by passing the context as the sole argument to "
299 .BR poptResetContext() .
300 .sp
301 When argument processing is complete, the process should free the 
302 .BR poptContext " as it contains dynamically allocated components. The "
303 .BR poptFreeContext() " function takes a " 
304 .BR poptContext " as its sole argument and frees the resources the "
305 context is using.
306 .sp
307 .RB "Here are the prototypes of both " poptResetContext() " and "
308 .BR poptFreeContext() :
309 .sp
310 .nf
311 .B #include <popt.h>
312 .BI "void poptFreeContext(poptContext " con ");"
313 .BI "void poptResetContext(poptContext " con ");"
314 .fi
315 .sp
316 .SS "3. PARSING THE COMMAND LINE"
317 .RB "After an application has created a " poptContext ", it may begin "
318 .RB "parsing arguments. " poptGetNextOpt() " performs the actual "
319 argument parsing.
320 .sp
321 .nf
322 .B #include <popt.h>
323 .BI "int poptGetNextOpt(poptContext " con ");"
324 .fi
325 .sp
326 Taking the context as its sole argument, this function parses the next
327 command-line argument found. After finding the next argument in the
328 option table, the function fills in the object pointed to by the option 
329 .RI "table entry's " arg 
330 .RB "pointer if it is not " NULL ". If the val entry for the option is "
331 non-0, the function then returns that value. Otherwise, 
332 .BR poptGetNextOpt() " continues on to the next argument."
333 .sp
334 .BR poptGetNextOpt() " returns -1 when the final argument has been "
335 parsed, and other negative values when errors occur. This makes it a 
336 good idea to 
337 .RI "keep the " val " elements in the options table greater than 0."
338 .sp
339 .RI "If all of the command-line options are handled through " arg 
340 pointers, command-line parsing is reduced to the following line of code:
341 .sp
342 .nf
343 rc = poptGetNextOpt(poptcon);
344 .fi
345 .sp
346 Many applications require more complex command-line parsing than this,
347 however, and use the following structure:
348 .sp
349 .nf
350 while ((rc = poptGetNextOpt(poptcon)) > 0) {
351      switch (rc) {
352           /* specific arguments are handled here */
353      }
354 }
355 .fi
356 .sp
357 When returned options are handled, the application needs to know the
358 value of any arguments that were specified after the option. There are two
359 ways to discover them. One is to ask popt to fill in a variable with the 
360 .RI "value of the option through the option table's " arg " elements. The "
361 .RB "other is to use " poptGetOptArg() ":"
362 .sp
363 .nf
364 .B #include <popt.h>
365 .BI "const char * poptGetOptArg(poptContext " con ");"
366 .fi
367 .sp
368 This function returns the argument given for the final option returned by
369 .BR poptGetNextOpt() ", or it returns " NULL " if no argument was specified."
370 .sp
371 .SS "4. LEFTOVER ARGUMENTS"
372 Many applications take an arbitrary number of command-line arguments,
373 such as a list of file names. When popt encounters an argument that does
374 not begin with a -, it assumes it is such an argument and adds it to a list
375 of leftover arguments. Three functions allow applications to access such
376 arguments:
377 .nf
378 .HP
379 .BI "const char * poptGetArg(poptContext " con ");"
380 .fi
381 This function returns the next leftover argument and marks it as
382 processed.
383 .PP
384 .nf
385 .HP
386 .BI "const char * poptPeekArg(poptContext " con ");"
387 .fi
388 The next leftover argument is returned but not marked as processed.
389 This allows an application to look ahead into the argument list,
390 without modifying the list.
391 .PP
392 .nf
393 .HP
394 .BI "const char ** poptGetArgs(poptContext " con ");"
395 .fi
396 All the leftover arguments are returned in a manner identical to 
397 .IR argv ".  The final element in the returned array points to "
398 .BR NULL ", indicating the end of the arguments.
399 .sp
400 .SS "5. AUTOMATIC HELP MESSAGES"
401 The \fBpopt\fR library can automatically generate help messages which
402 describe the options a program accepts. There are two types of help
403 messages which can be generated. Usage messages are a short messages
404 which lists valid options, but does not describe them. Help messages
405 describe each option on one (or more) lines, resulting in a longer, but
406 more useful, message. Whenever automatic help messages are used, the
407 \fBdescrip\fR and \fBargDescrip\fR fields \fBstruct poptOption\fR members
408 should be filled in for each option.
409 .sp
410 The \fBPOPT_AUTOHELP\fR macro makes it easy to add \fB--usage\fR and
411 \fB--help\fR messages to your program, and is described in part 1
412 of this man page. If more control is needed over your help messages,
413 the following two functions are available:
414 .sp
415 .nf
416 .B #include <popt.h>
417 .BI "void poptPrintHelp(poptContext " con ", FILE * " f ", int " flags ");
418 .BI "void poptPrintUsage(poptContext " con ", FILE * " f ", int " flags ");
419 .fi
420 .sp
421 \fBpoptPrintHelp()\fR displays the standard help message to the stdio file
422 descriptor f, while \fBpoptPrintUsage()\fR displays the shorter usage
423 message. Both functions currently ignore the \fBflags\fR argument; it is
424 there to allow future changes.
425 .sp
426 .SH "ERROR HANDLING"
427 All of the popt functions that can return errors return integers. 
428 When an error occurs, a negative error code is returned. The 
429 following table summarizes the error codes that occur:
430 .sp
431 .nf
432 .B "     Error                      Description"
433 .BR "POPT_ERROR_NOARG       " "Argument missing for an option."
434 .BR "POPT_ERROR_BADOPT      " "Option's argument couldn't be parsed."
435 .BR "POPT_ERROR_OPTSTOODEEP " "Option aliasing nested too deeply."
436 .BR "POPT_ERROR_BADQUOTE    " "Quotations do not match."
437 .BR "POPT_ERROR_BADNUMBER   " "Option couldn't be converted to number."
438 .BR "POPT_ERROR_OVERFLOW    " "A given number was too big or small."
439 .fi
440 .sp
441 Here is a more detailed discussion of each error:
442 .sp
443 .TP
444 .B POPT_ERROR_NOARG
445 An option that requires an argument was specified on the command
446 line, but no argument was given. This can be returned only by
447 .BR poptGetNextOpt() .
448 .sp
449 .TP
450 .B POPT_ERROR_BADOPT
451 .RI "An option was specified in " argv " but is not in the option 
452 .RB "table. This error can be returned only from " poptGetNextOpt() .
453 .sp
454 .TP
455 .B POPT_ERROR_OPTSTOODEEP
456 A set of option aliases is nested too deeply. Currently, popt 
457 follows options only 10 levels to prevent infinite recursion. Only 
458 .BR poptGetNextOpt() " can return this error."
459 .sp
460 .TP
461 .B POPT_ERROR_BADQUOTE
462 A parsed string has a quotation mismatch (such as a single quotation
463 .RB "mark). " poptParseArgvString() ", " poptReadConfigFile() ", or "
464 .BR poptReadDefaultConfig() " can return this error."
465 .sp
466 .TP
467 .B POPT_ERROR_BADNUMBER
468 A conversion from a string to a number (int or long) failed due
469 to the string containing nonnumeric characters. This occurs when
470 .BR poptGetNextOpt() " is processing an argument of type " 
471 .BR POPT_ARG_INT ", " POPT_ARG_LONG ", "
472 .RB POPT_ARG_FLOAT ", or " POPT_ARG_DOUBLE "."  
473 .sp
474 .TP
475 .B POPT_ERROR_OVERFLOW
476 A string-to-number conversion failed because the number was too
477 .RB "large or too small. Like " POPT_ERROR_BADNUMBER ", this error 
478 .RB "can occur only when " poptGetNextOpt() " is processing an "
479 .RB "argument of type " POPT_ARG_INT ", " POPT_ARG_LONG ", "
480 .RB POPT_ARG_FLOAT ", or " POPT_ARG_DOUBLE "."  
481 .sp
482 .TP
483 .B POPT_ERROR_ERRNO
484 .RI "A system call returned with an error, and " errno " still 
485 contains the error from the system call. Both 
486 .BR poptReadConfigFile() " and " poptReadDefaultConfig() " can "
487 return this error.
488 .sp
489 .PP
490 Two functions are available to make it easy for applications to provide
491 good error messages.
492 .HP
493 .nf
494 .BI "const char *const poptStrerror(const int " error ");"
495 .fi
496 This function takes a popt error code and returns a string describing
497 .RB "the error, just as with the standard " strerror() " function."
498 .PP
499 .HP
500 .nf
501 .BI "const char * poptBadOption(poptContext " con ", int " flags ");"
502 .fi
503 .RB "If an error occurred during " poptGetNextOpt() ", this function "
504 .RI "returns the option that caused the error. If the " flags " argument"
505 .RB "is set to " POPT_BADOPTION_NOALIAS ", the outermost option is "
506 .RI "returned. Otherwise, " flags " should be 0, and the option that is "
507 returned may have been specified through an alias.
508 .PP
509 These two functions make popt error handling trivial for most 
510 applications. When an error is detected from most of the functions, 
511 an error message is printed along with the error string from 
512 .BR poptStrerror() ". When an error occurs during argument parsing, "
513 code similiar to the following displays a useful error message:
514 .sp
515 .nf
516 fprintf(stderr, "%s: %s\\n",
517         poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
518         poptStrerror(rc));
519 .fi
520 .sp
521 .SH "OPTION ALIASING"
522 .RB "One of the primary benefits of using popt over " getopt() " is the "
523 ability to use option aliasing. This lets the user specify options that 
524 popt expands into other options when they are specified. If the standard 
525 .RB "grep program made use of popt, users could add a " --text " option "
526 .RB "that expanded to " "-i -n -E -2" " to let them more easily find "
527 information in text files.
528 .sp
529 .SS "1. SPECIFYING ALIASES"
530 .RI "Aliases are normally specified in two places: " /etc/popt 
531 .RB "and the " .popt " file in the user's home directory (found through "
532 .RB "the " HOME " environment variable). Both files have the same format, "
533 an arbitrary number of lines formatted like this:
534 .sp
535 .IB appname " alias " newoption "" " expansion"
536 .sp
537 .RI "The " appname " is the name of the application, which must be the "
538 .RI "same as the " name " parameter passed to "
539 .BR poptGetContext() ". This allows each file to specify aliases for "
540 .RB "multiple programs. The " alias " keyword specifies that an alias is "
541 being defined; currently popt configuration files support only aliases, but
542 other abilities may be added in the future. The next option is the option
543 that should be aliased, and it may be either a short or a long option. The
544 rest of the line specifies the expansion for the alias. It is parsed 
545 similarly to a shell command, which allows \\, ", and ' to be used for 
546 quoting. If a backslash is the final character on a line, the next line 
547 in the file is assumed to be a logical continuation of the line containing 
548 the backslash, just as in shell.
549 .sp
550 .RB "The following entry would add a " --text " option to the grep command, "
551 as suggested at the beginning of this section.
552 .sp
553 .B "grep alias --text -i -n -E -2"
554 .SS "2. ENABLING ALIASES"
555 .RB "An application must enable alias expansion for a " poptContext 
556 .RB "before calling " poptGetNextArg() " for the first time. There are "
557 three functions that define aliases for a context:
558 .HP
559 .nf
560 .BI "int poptReadDefaultConfig(poptContext " con ", int " flags ");"
561 .fi
562 .RI "This function reads aliases from " /etc/popt " and the "
563 .BR .popt " file in the user's home directory. Currently, "
564 .IR flags " should be "
565 .BR NULL ", as it is provided only for future expansion."
566 .PP
567 .HP
568 .nf
569 .BI "int poptReadConfigFile(poptContext " con ", char * " fn ");"
570 .fi
571 .RI "The file specified by " fn " is opened and parsed as a popt "
572 configuration file. This allows programs to use program-specific 
573 configuration files.
574 .PP
575 .HP
576 .nf
577 .BI "int poptAddAlias(poptContext " con ", struct poptAlias " alias ",
578 .BI "                 int " flags ");"
579 .fi
580 Occasionally, processes want to specify aliases without having to
581 read them from a configuration file. This function adds a new alias
582 .RI "to a context. The " flags " argument should be 0, as it is "
583 currently reserved for future expansion. The new alias is specified 
584 .RB "as a " "struct poptAlias" ", which is defined as:"
585 .sp
586 .nf
587 struct poptAlias {
588      const char * longName; /* may be NULL */
589      char shortName; /* may be '\\0' */
590      int argc;
591      const char ** argv; /* must be free()able */
592 };
593 .fi
594 .sp
595 .RI "The first two elements, " longName " and " shortName ", specify "
596 .RI "the option that is aliased. The final two, " argc " and " argv ","
597 define the expansion to use when the aliases option is encountered.
598 .PP
599 .SH "PARSING ARGUMENT STRINGS"
600 Although popt is usually used for parsing arguments already divided into
601 .RI "an " argv "-style array, some programs need to parse strings that "
602 are formatted identically to command lines. To facilitate this, popt 
603 provides a function that parses a string into an array of strings, 
604 using rules similiar to normal shell parsing.
605 .sp
606 .nf
607 .B "#include <popt.h>"
608 .BI "int poptParseArgvString(char * " s ", int * " argcPtr ",
609 .BI "                        char *** " argvPtr ");"
610 .BI "int poptDupArgv(int " argc ", const char ** " argv ", int * " argcPtr ",
611 .BI "                        const char *** " argvPtr ");"
612 .fi
613 .sp
614 .RI "The string s is parsed into an " argv "-style array. The integer "
615 .RI "pointed to by the " argcPtr " parameter contains the number of elements "
616 .RI "parsed, and the final " argvPtr " parameter contains the address of the"
617 newly created array.
618 .RB "The routine " poptDupArgv() " can be used to make a copy of an existing "
619 argument array.
620 .sp
621 .RI "The " argvPtr 
622 .RB "created by " poptParseArgvString() " or " poptDupArgv() " is suitable to pass directly "
623 .RB "to " poptGetContext() .
624 Both routines return a single dynamically allocated contiguous
625 .RB "block of storage and should be " free() "ed when the application is"
626 finished with the storage.
627 .SH "HANDLING EXTRA ARGUMENTS"
628 Some applications implement the equivalent of option aliasing but need
629 .RB "to do so through special logic. The " poptStuffArgs() " function "
630 allows an application to insert new arguments into the current 
631 .BR poptContext .
632 .sp
633 .nf
634 .B "#include <popt.h>"
635 .BI "int poptStuffArgs(poptContext "con ", const char ** " argv ");"
636 .fi
637 .sp
638 .RI "The passed " argv 
639 .RB "must have a " NULL " pointer as its final element. When "
640 .BR poptGetNextOpt() " is next called, the "
641 "stuffed" arguments are the first to be parsed. popt returns to the 
642 normal arguments once all the stuffed arguments have been exhausted.
643 .SH "EXAMPLE"
644 The following example is a simplified version of the program "robin" 
645 which appears in Chapter 15 of the text cited below.  Robin has 
646 been stripped of everything but its argument-parsing logic, slightly 
647 reworked, and renamed "parse." It may prove useful in illustrating 
648 at least some of the features of the extremely rich popt library.
649 .sp
650 .nf
651 #include <popt.h>
652 #include <stdio.h>
653
654 void usage(poptContext optCon, int exitcode, char *error, char *addl) {
655     poptPrintUsage(optCon, stderr, 0);
656     if (error) fprintf(stderr, "%s: %s\n", error, addl);
657     exit(exitcode);
658 }
659
660 int main(int argc, char *argv[]) {
661    char    c;            /* used for argument parsing */
662    int     i = 0;        /* used for tracking options */
663    char    *portname;
664    int     speed = 0;    /* used in argument parsing to set speed */
665    int     raw = 0;      /* raw mode? */ 
666    int     j;
667    char    buf[BUFSIZ+1];
668    poptContext optCon;   /* context for parsing command-line options */
669
670    struct poptOption optionsTable[] = {
671             { "bps", 'b', POPT_ARG_INT, &speed, 0,
672                 "signaling rate in bits-per-second", "BPS" },
673             { "crnl", 'c', 0, 0, 'c',
674                 "expand cr characters to cr/lf sequences" },
675             { "hwflow", 'h', 0, 0, 'h',
676                 "use hardware (RTS/CTS) flow control" },
677             { "noflow", 'n', 0, 0, 'n',
678                 "use no flow control" },
679             { "raw", 'r', 0, &raw, 0,
680                 "don't perform any character conversions" },
681             { "swflow", 's', 0, 0, 's',
682                 "use software (XON/XOF) flow control" } ,
683             POPT_AUTOHELP
684             { NULL, 0, 0, NULL, 0 }
685    };
686
687    optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
688    poptSetOtherOptionHelp(optCon, "[OPTIONS]* <port>");
689
690    if (argc < 2) {
691         poptPrintUsage(optCon, stderr, 0);
692         exit(1);
693    }
694
695    /* Now do options processing, get portname */
696    while ((c = poptGetNextOpt(optCon)) >= 0) {
697       switch (c) {
698          case 'c': 
699             buf[i++] = 'c';         
700             break;
701          case 'h': 
702             buf[i++] = 'h';
703             break;
704          case 's':
705             buf[i++] = 's';
706             break;
707          case 'n':
708             buf[i++] = 'n';
709             break;
710       }
711    }
712    portname = poptGetArg(optCon);
713    if((portname == NULL) || !(poptPeekArg(optCon) == NULL))
714       usage(optCon, 1, "Specify a single port", ".e.g., /dev/cua0");
715
716    if (c < -1) {
717       /* an error occurred during option processing */
718       fprintf(stderr, "%s: %s\\n", 
719               poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
720               poptStrerror(c));
721       return 1;
722    }
723
724    /* Print out options, portname chosen */
725    printf("Options  chosen: ");
726    for(j = 0; j < i ; j++)
727       printf("-%c ", buf[j]);
728    if(raw) printf("-r ");
729    if(speed) printf("-b %d ", speed);
730    printf("\\nPortname chosen: %s\\n", portname);
731
732    poptFreeContext(optCon);
733    exit(0);
734 }
735 .fi
736 .sp
737 RPM, a popular Linux package management program, makes heavy use
738 of popt's features. Many of its command-line arguments are implemented
739 through popt aliases, which makes RPM an excellent example of how to
740 take advantage of the popt library. For more information on RPM, see
741 http://www.rpm.org. The popt source code distribution includes test
742 program(s) which use all of the features of the popt libraries in
743 various ways. If a feature isn't working for you, the popt test code
744 is the first place to look.
745 .SH BUGS
746 None presently known.
747 .SH AUTHOR
748 Erik W. Troan <ewt@redhat.com>
749 .PP
750 This man page is derived in part from
751 .IR "Linux Application Development"
752 by Michael K. Johnson and Erik W. Troan, Copyright (c) 1998 by Addison
753 Wesley Longman, Inc., and included in the popt documentation with the
754 permission of the Publisher and the appreciation of the Authors.
755 .PP
756 Thanks to Robert Lynch for his extensive work on this man page.
757 .SH "SEE ALSO"
758 .BR getopt (3)
759 .sp
760 .IR "Linux Application Development" ", by Michael K. Johnson and "
761 Erik W. Troan (Addison-Wesley, 1998; ISBN 0-201-30821-5), Chapter 24.
762 .sp
763 .BR popt.ps " is a Postscript version of the above cited book "
764 chapter. It can be found in the source archive for popt available at: 
765 ftp://ftp.rpm.org/pub/rpm.