Debian Codegraph @

popt.3

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