1POPT(3)                    Linux Programmer's Manual                   POPT(3)
2
3
4

NAME

6       popt - Parse command line options
7

SYNOPSIS

9       #include <popt.h>
10
11       poptContext poptGetContext(const char * name, int argc,
12                                  const char ** argv,
13                                  const struct poptOption * options,
14                                  unsigned int flags);
15
16       void poptFreeContext(poptContext con);
17
18       void poptResetContext(poptContext con);
19
20       int poptGetNextOpt(poptContext con);
21
22       const char * poptGetOptArg(poptContext con);
23
24       const char * poptGetArg(poptContext con);
25
26       const char * poptPeekArg(poptContext con);
27
28       const char ** poptGetArgs(poptContext con);
29
30       const char *const poptStrerror(const int error);
31
32       const char * poptBadOption(poptContext con, int flags);
33
34       int poptReadDefaultConfig(poptContext con, int flags);
35
36       int poptReadConfigFile(poptContext con, char * fn);
37
38       int poptAddAlias(poptContext con, struct poptAlias alias,
39                        int flags);
40
41       int poptParseArgvString(char * s, int *  argcPtr,
42                               const char *** argvPtr);
43
44       int poptDupArgv(int argc, const char ** argv, int * argcPtr,
45                               const char *** argvPtr);
46
47       int poptStuffArgs(poptContext con, const char ** argv);
48
49

DESCRIPTION

51       The  popt  library exists essentially for parsing command-line options.
52       It is found superior in many ways when compared to parsing the argv ar‐
53       ray  by  hand  or using the getopt functions getopt() and getopt_long()
54       [see getopt(3)].  Some specific advantages of popt  are:  it  does  not
55       utilize global variables, thus enabling multiple passes in parsing argv
56       ; it can parse an arbitrary  array  of  argv-style  elements,  allowing
57       parsing of command-line-strings from any source; it provides a standard
58       method of option aliasing (to be discussed at length  below.);  it  can
59       exec external option filters; and, finally, it can automatically gener‐
60       ate help and usage messages for the application.
61
62       Like getopt_long(), the popt library supports short and long style  op‐
63       tions.   Recall  that a short option consists of a - character followed
64       by a single alphanumeric character.  A long option, common in GNU util‐
65       ities,  consists  of  two  - characters followed by a string made up of
66       letters, numbers and hyphens.  Long options are optionally  allowed  to
67       begin  with  a  single -, primarily to allow command-line compatibility
68       between popt applications and X toolkit applications.  Either  type  of
69       option  may  be followed by an argument.  A space separates a short op‐
70       tion from its arguments; either a space or an = separates a long option
71       from an argument.
72
73       The  popt library is highly portable and should work on any POSIX plat‐
74       form.  The latest version is distributed with rpm and is always  avail‐
75       able from: ftp://ftp.rpm.org/pub/rpm/dist.
76
77       It  may  be  redistributed under the X consortium license, see the file
78       COPYING in the popt source distribution for details.
79

BASIC POPT USAGE

81   1. THE OPTION TABLE
82       Applications provide popt with information on  their  command-line  op‐
83       tions  by  means of an "option table," i.e., an array of struct poptOp‐
84       tion structures:
85
86       #include <popt.h>
87
88       struct poptOption {
89           const char * longName;   /* may be NULL */
90           char shortName;          /* may be '\0' */
91           unsigned int argInfo;    /* type of argument expected after the option */
92           void * arg;              /* depends on argInfo */
93           int val;                 /* 0 means don't return, just update arg */
94           const char * descrip;    /* description for autohelp -- may be NULL */
95           const char * argDescrip; /* argument description for autohelp -- may be NULL*/
96       };
97
98       Each member of the table defines a single option that may be passed  to
99       the  program.   Long  and  short options are considered a single option
100       that may occur in two different forms.  The first two members, longName
101       and  shortName,  define  the  names  of the option; the first is a long
102       name, while the latter is a single character.
103
104       The argInfo member tells popt what type of argument is  expected  after
105       the  option.  If no argument is expected, POPT_ARG_NONE should be used.
106       The valid values of argInfo are shown in the following table:
107
108
109       Value               Description                        arg Type
110       POPT_ARG_NONE       No argument expected               int
111       POPT_ARG_STRING     No type checking to be performed   char *
112       POPT_ARG_ARGV       No type checking to be performed   char **
113       POPT_ARG_SHORT      A short argument is expected       short
114       POPT_ARG_INT        An integer argument is expected    int
115       POPT_ARG_LONG       A long integer is expected         long
116       POPT_ARG_LONGLONG   A long long integer is expected    long long
117       POPT_ARG_VAL        Integer value taken from val       int
118       POPT_ARG_FLOAT      A float argument is expected       float
119       POPT_ARG_DOUBLE     A double argument is expected      double
120
121       For numeric values, if the argInfo value is bitwise or'd  with  one  of
122       POPT_ARGFLAG_OR,  POPT_ARGFLAG_AND,  or  POPT_ARGFLAG_XOR, the value is
123       saved by performing an OR, AND, or XOR.  If the argInfo value  is  bit‐
124       wise  or'd with POPT_ARGFLAG_NOT, the value will be negated before sav‐
125       ing. For  the  common  operations  of  setting  and/or  clearing  bits,
126       POPT_BIT_SET and POPT_BIT_CLR have the appropriate flags set to perform
127       bit operations.
128
129       If the argInfo value is bitwise  or'd  with  POPT_ARGFLAG_ONEDASH,  the
130       long argument may be given with a single - instead of two. For example,
131       if --longopt is an  option  with  POPT_ARGFLAG_ONEDASH,  is  specified,
132       -longopt is accepted as well.
133
134       The  next  element,  arg,  allows  popt to automatically update program
135       variables when the option is used. If arg is NULL, it  is  ignored  and
136       popt  takes no special action.  Otherwise it should point to a variable
137       of the type indicated in the right-most column of the  table  above.  A
138       POPT_ARG_ARGV  arg  will (re-)allocate an array of char * string point‐
139       ers, append the string argument, and add a NULL sentinel at the end  of
140       the array as needed.  The target char ** address of a POPT_ARG_ARGV arg
141       should be initialized to NULL.
142
143       If the option takes no argument (argInfo is POPT_ARG_NONE),  the  vari‐
144       able  pointed to by arg is set to 1 when the option is used.  (Inciden‐
145       tally, it will perhaps not escape the attention of  hunt-and-peck  typ‐
146       ists that the value of POPT_ARG_NONE is 0.)  If the option does take an
147       argument, the variable that arg points to is  updated  to  reflect  the
148       value  of  the  argument.  Any string is acceptable for POPT_ARG_STRING
149       and  POPT_ARG_ARGV   arguments,   but   POPT_ARG_INT,   POPT_ARG_SHORT,
150       POPT_ARG_LONG,  POPT_ARG_LONGLONG,  POPT_ARG_FLOAT, and POPT_ARG_DOUBLE
151       are converted to the appropriate type, and an  error  returned  if  the
152       conversion fails.
153
154       POPT_ARG_VAL  causes  arg  to be set to the (integer) value of val when
155       the argument is found.  This is most often useful  for  mutually-exclu‐
156       sive arguments in cases where it is not an error for multiple arguments
157       to occur and where you want the last argument specified to win; for ex‐
158       ample, "rm -i -f".  POPT_ARG_VAL causes the parsing function not to re‐
159       turn a value, since the value of val has already been used.
160
161       If the argInfo value is bitwise or'd  with  POPT_ARGFLAG_OPTIONAL,  the
162       argument  to the long option may be omitted. If the long option is used
163       without an argument, a default value of zero or NULL will be saved  (if
164       the  arg pointer is present), otherwise behavior will be identical to a
165       long option with argument.
166
167       The next option, val, is the value popt's parsing function  should  re‐
168       turn  when the option is encountered.  If it is 0, the parsing function
169       does not return a value, instead parsing the  next  command-line  argu‐
170       ment.
171
172       The last two options, descrip and argDescrip are only required if auto‐
173       matic help messages are desired (automatic usage messages can be gener‐
174       ated  without  them). descrip is a text description of the argument and
175       argDescrip is a short summary of the type of arguments the  option  ex‐
176       pects, or NULL if the option doesn't require any arguments.
177
178       If  popt should automatically provide --usage and --help (-?)  options,
179       one line in the table should be the macro  POPT_AUTOHELP.   This  macro
180       includes  another option table (via POPT_ARG_INCLUDE_TABLE ; see below)
181       in the main one which provides the table entries for  these  arguments.
182       When  --usage  or  --help are passed to programs which use popt's auto‐
183       matic help, popt displays the appropriate message on stderr as soon  as
184       it  finds the option, and exits the program with a return code of 0. If
185       you want to use popt's automatic help generation in  a  different  way,
186       you  need  to explicitly add the option entries to your programs option
187       table instead of using POPT_AUTOHELP.
188
189       If the argInfo value is bitwise or'd with POPT_ARGFLAG_DOC_HIDDEN,  the
190       argument will not be shown in help output.
191
192       If  the  argInfo  value is bitwise or'd with POPT_ARGFLAG_SHOW_DEFAULT,
193       the initial value of the arg will be shown in help output.
194
195       The final structure in the table should have all the pointer values set
196       to  NULL and all the arithmetic values set to 0, marking the end of the
197       table. The macro POPT_TABLEEND is provided to do that.
198
199       There are two types of option table entries which do not  specify  com‐
200       mand  line options. When either of these types of entries are used, the
201       longName element must be NULL and the shortName element must be '\0'.
202
203       The first of these special entry types allows the application  to  nest
204       another  option table in the current one; such nesting may extend quite
205       deeply (the actual depth is limited by the program's stack).  Including
206       other  option tables allows a library to provide a standard set of com‐
207       mand-line options to every program which uses it (this is often done in
208       graphical  programming  toolkits,  for  example).  To  do this, set the
209       argInfo field to POPT_ARG_INCLUDE_TABLE and the arg field to  point  to
210       the  table which is being included. If automatic help generation is be‐
211       ing used, the descrip field should contain an  overall  description  of
212       the option table being included.
213
214       The other special option table entry type tells popt to call a function
215       (a callback) when any option in that table is found. This is especially
216       useful when included option tables are being used, as the program which
217       provides the top-level option table doesn't need to  be  aware  of  the
218       other options which are provided by the included table. When a callback
219       is set for a table, the parsing function never returns  information  on
220       an  option  in the table. Instead, options information must be retained
221       via the callback or by having popt set a variable through the  option's
222       arg field.  Option callbacks should match the following prototype:
223
224       void poptCallbackType(poptContext con,
225                             const struct poptOption * opt,
226                             const char * arg, void * data);
227
228       The  first parameter is the context which is being parsed (see the next
229       section for information on contexts), opt points to  the  option  which
230       triggered  this callback, and arg is the option's argument.  If the op‐
231       tion does not take an argument, arg is NULL.  The final parameter, data
232       is taken from the descrip field of the option table entry which defined
233       the callback. As descrip is a pointer, this allows  callback  functions
234       to  be  passed an arbitrary set of data (though a typecast will have to
235       be used).
236
237       The option table entry which defines  a  callback  has  an  argInfo  of
238       POPT_ARG_CALLBACK,  an arg which points to the callback function, and a
239       descrip field which specifies an arbitrary pointer to be passed to  the
240       callback.
241
242   2. CREATING A CONTEXT
243       popt  can  interleave the parsing of multiple command-line sets. It al‐
244       lows this by keeping all the state information for a particular set  of
245       command-line  arguments in a poptContext data structure, an opaque type
246       that should not be modified outside the popt library.
247
248       New popt contexts are created by poptGetContext():
249
250       poptContext poptGetContext(const char * name, int argc,
251                                  const char ** argv,
252                                  const struct poptOption * options,
253                                  unsigned int flags);
254
255       The first parameter, name, is used only for alias  handling  (discussed
256       later).  It should be the name of the application whose options are be‐
257       ing parsed, or should be NULL if no option  aliasing  is  desired.  The
258       next  two  arguments specify the command-line arguments to parse. These
259       are generally passed to poptGetContext() exactly as they were passed to
260       the  program's main() function. The options parameter points to the ta‐
261       ble of command-line options, which was described in the  previous  sec‐
262       tion.  The final parameter, flags, can be any bitwise or combination of
263       the following four values:
264
265       Value                        Description
266       POPT_CONTEXT_NO_EXEC         Ignore exec expansions
267       POPT_CONTEXT_KEEP_FIRST      Do not ignore argv[0]
268       POPT_CONTEXT_POSIXMEHARDER   Options cannot follow arguments
269       POPT_CONTEXT_ARG_OPTS        Return the arguments as options of value 0
270
271       A poptContext keeps track of which options have already been parsed and
272       which remain, among other things. If a program wishes to restart option
273       processing of a set of arguments, it can reset the poptContext by pass‐
274       ing the context as the sole argument to poptResetContext().
275
276       When argument processing is complete, the process should free the popt‐
277       Context as it contains  dynamically  allocated  components.  The  popt‐
278       FreeContext()  function  takes  a  poptContext as its sole argument and
279       frees the resources the context is using.
280
281       Here are the prototypes of  both  poptResetContext()  and  poptFreeCon‐
282       text():
283
284       #include <popt.h>
285       void poptFreeContext(poptContext con);
286       void poptResetContext(poptContext con);
287
288
289   3. PARSING THE COMMAND LINE
290       After  an  application  has created a poptContext, it may begin parsing
291       arguments. poptGetNextOpt() performs the actual argument parsing.
292
293       #include <popt.h>
294       int poptGetNextOpt(poptContext con);
295
296       Taking the context as its sole argument, this function parses the  next
297       command-line argument found. After finding the next argument in the op‐
298       tion table, the function fills in the object pointed to by  the  option
299       table  entry's  arg pointer if it is not NULL. If the val entry for the
300       option is non-0, the function then returns that value. Otherwise, popt‐
301       GetNextOpt() continues on to the next argument.
302
303       poptGetNextOpt()  returns  -1  when the final argument has been parsed,
304       and other negative values when errors occur. This makes it a good  idea
305       to keep the val elements in the options table greater than 0.
306
307       If  all  of  the command-line options are handled through arg pointers,
308       command-line parsing is reduced to the following line of code:
309
310       rc = poptGetNextOpt(poptcon);
311
312       Many applications require more complex command-line parsing than  this,
313       however, and use the following structure:
314
315       while ((rc = poptGetNextOpt(poptcon)) > 0) {
316            switch (rc) {
317                 /* specific arguments are handled here */
318            }
319       }
320
321       When  returned  options  are handled, the application needs to know the
322       value of any arguments that were specified after the option. There  are
323       two  ways  to  discover  them. One is to ask popt to fill in a variable
324       with the value of the option through the option table's  arg  elements.
325       The other is to use poptGetOptArg():
326
327       #include <popt.h>
328       char * poptGetOptArg(poptContext con);
329
330       This  function returns the argument given for the final option returned
331       by poptGetNextOpt(), or it returns NULL if no argument  was  specified.
332       The calling function is responsible for deallocating this string.
333
334
335   4. LEFTOVER ARGUMENTS
336       Many  applications  take an arbitrary number of command-line arguments,
337       such as a list of file names. When popt  encounters  an  argument  that
338       does  not begin with a -, it assumes it is such an argument and adds it
339       to a list of leftover arguments. Three functions allow applications  to
340       access such arguments:
341
342       const char * poptGetArg(poptContext con);
343              This function returns the next leftover argument and marks it as
344              processed.
345
346       const char * poptPeekArg(poptContext con);
347              The next leftover argument is returned but not  marked  as  pro‐
348              cessed.  This allows an application to look ahead into the argu‐
349              ment list, without modifying the list.
350
351       const char ** poptGetArgs(poptContext con);
352              All the leftover arguments are returned in a manner identical to
353              argv.   The  final element in the returned array points to NULL,
354              indicating the end of the arguments.
355
356
357   5. AUTOMATIC HELP MESSAGES
358       The popt library can automatically generate  help  messages  which  de‐
359       scribe  the options a program accepts. There are two types of help mes‐
360       sages which can be generated. Usage messages are a short messages which
361       lists valid options, but does not describe them. Help messages describe
362       each option on one (or more) lines, resulting in  a  longer,  but  more
363       useful, message. Whenever automatic help messages are used, the descrip
364       and argDescrip fields struct poptOption members should be filled in for
365       each option.
366
367       The  POPT_AUTOHELP  macro  makes it easy to add --usage and --help mes‐
368       sages to your program, and is described in part 1 of this man page.  If
369       more control is needed over your help messages, the following two func‐
370       tions are available:
371
372       #include <popt.h>
373       void poptPrintHelp(poptContext con, FILE * f, int flags);
374       void poptPrintUsage(poptContext con, FILE * f, int flags);
375
376       poptPrintHelp() displays the standard help message to  the  stdio  file
377       descriptor  f,  while  poptPrintUsage() displays the shorter usage mes‐
378       sage. Both functions currently ignore the flags argument; it  is  there
379       to allow future changes.
380
381

ERROR HANDLING

383       All of the popt functions that can return errors return integers.  When
384       an error occurs, a negative error code is returned. The following table
385       summarizes the error codes that occur:
386
387
388       Error                     Description
389       POPT_ERROR_NOARG          Argument missing for an option.
390       POPT_ERROR_BADOPT         Option's argument couldn't be parsed.
391       POPT_ERROR_UNWANTEDARG    Option does not take an argument.
392       POPT_ERROR_OPTSTOODEEP    Option aliasing nested too deeply.
393       POPT_ERROR_BADQUOTE       Quotations do not match.
394       POPT_ERROR_ERRNO          errno set, use strerror(errno).
395       POPT_ERROR_BADNUMBER      Option couldn't be converted to number.
396
397       POPT_ERROR_OVERFLOW       A given number was too big or small.
398       POPT_ERROR_BADOPERATION   Mutually exclusive logical operations requested.
399       POPT_ERROR_NULLARG        opt->arg should not be NULL.
400       POPT_ERROR_MALLOC         Memory allocation failed.
401       POPT_ERROR_BADCONFIG      Config file failed sanity test.
402
403       Here is a more detailed discussion of each error:
404
405
406       POPT_ERROR_NOARG
407              An option that requires an argument was specified on the command
408              line, but no argument was given. This can be  returned  only  by
409              poptGetNextOpt().
410
411
412       POPT_ERROR_BADOPT
413              An  option was specified in argv but is not in the option table.
414              This error can be returned only from poptGetNextOpt().
415
416
417       POPT_ERROR_OPTSTOODEEP
418              A set of option aliases is nested too  deeply.  Currently,  popt
419              follows  options  only  10 levels (POPT_OPTION_DEPTH) to prevent
420              infinite recursion. Only poptGetNextOpt() can return this error.
421
422
423       POPT_ERROR_BADQUOTE
424              A parsed string has a quotation mismatch (such as a single  quo‐
425              tation  mark).  poptParseArgvString(),  poptReadConfigFile(), or
426              poptReadDefaultConfig() can return this error.
427
428
429       POPT_ERROR_ERRNO
430              A system call returned with an error, and errno  still  contains
431              the  error  from  the system call. Both poptReadConfigFile() and
432              poptReadDefaultConfig() can return this error.
433
434
435       POPT_ERROR_BADNUMBER
436              A conversion from a string to a number (int or long) failed  due
437              to  the  string  containing  non-numeric characters. This occurs
438              when  poptGetNextOpt()  is  processing  an  argument   of   type
439              POPT_ARG_INT,  POPT_ARG_SHORT, POPT_ARG_LONG, POPT_ARG_LONGLONG,
440              POPT_ARG_FLOAT, or POPT_ARG_DOUBLE.
441
442
443       POPT_ERROR_OVERFLOW
444              A string-to-number conversion failed because the number was  too
445              large  or  too  small. Like POPT_ERROR_BADNUMBER, this error can
446              occur only when poptGetNextOpt() is processing  an  argument  of
447              type POPT_ARG_INT, POPT_ARG_SHORT, POPT_ARG_LONG, POPT_ARG_LONG‐
448              LONG, POPT_ARG_FLOAT, or POPT_ARG_DOUBLE.
449
450
451       POPT_ERROR_BADOPERATION
452              More than one logical operation (AND, OR, XOR) was specified for
453              an option, or POPT_ARGFLAG_RANDOM was specified but the platform
454              does not support the random() function.  This  can  be  returned
455              only by poptSaveLongLong(), poptSaveLong(), poptSaveInt(), popt‐
456              SaveShort() and poptGetNextOpt().
457
458
459       POPT_ERROR_NULLARG
460              An operation was invoked on a null target arg  (including  zero-
461              length  string  arguments). In the poptBitsArgs() case, this in‐
462              cludes an empty leftover argv array. This can only  be  returned
463              by  the  poptBits*()  and poptSave*() functions, poptConfigFile‐
464              ToString() and poptGetNextOpt().
465
466
467       POPT_ERROR_MALLOC
468              Memory allocation failed. This can only be returned by poptRead‐
469              File(),  poptDupArgv(),  poptParseArgvString(),  poptConfigFile‐
470              ToString() and poptGetNextOpt().
471
472
473       POPT_ERROR_BADCONFIG
474              The popt configuration files are corrupted. This can only be re‐
475              turned by poptReadConfigFile() and poptReadConfigFiles().
476
477
478       Two functions are available to make it easy for applications to provide
479       good error messages.
480
481
482              const char *const poptStrerror(const int error);
483              This function takes a popt error code and returns a  string  de‐
484              scribing  the  error, just as with the standard strerror() func‐
485              tion.
486
487
488              const char * poptBadOption(poptContext con, int flags);
489              If an error occurred during poptGetNextOpt(), this function  re‐
490              turns the option that caused the error. If the flags argument is
491              set to POPT_BADOPTION_NOALIAS, the outermost option is returned.
492              Otherwise,  flags  should  be 0, and the option that is returned
493              may have been specified through an alias.
494
495       These two functions make popt error handling trivial for most  applica‐
496       tions.  When  an error is detected from most of the functions, an error
497       message is printed along with the  error  string  from  poptStrerror().
498       When  an error occurs during argument parsing, code similar to the fol‐
499       lowing displays a useful error message:
500
501       fprintf(stderr, "%s: %s\n",
502               poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
503               poptStrerror(rc));
504
505

OPTION ALIASING

507       One of the primary benefits of using popt over getopt() is the  ability
508       to  use  option  aliasing. This lets the user specify options that popt
509       expands into other options when they are  specified.  If  the  standard
510       grep program made use of popt, users could add a --text option that ex‐
511       panded to -i -n -E -2 to let them more easily find information in  text
512       files.
513
514
515   1. SPECIFYING ALIASES
516       Aliases  are  normally specified in two places: /etc/popt and the .popt
517       file in the user's home directory (found through the  HOME  environment
518       variable).  Both  files  have  the  same format, an arbitrary number of
519       lines formatted like this:
520
521       appname alias newoption expansion
522
523       The appname is the name of the application, which must be the  same  as
524       the name parameter passed to poptGetContext(). This allows each file to
525       specify aliases for multiple programs. The alias keyword specifies that
526       an  alias  is being defined; currently popt configuration files support
527       only aliases, but other abilities may be added in the future. The  next
528       option  is  the  option  that should be aliased, and it may be either a
529       short or a long option. The rest of the line  specifies  the  expansion
530       for  the alias. It is parsed similarly to a shell command, which allows
531       \, ", and ' to be used for quoting. If a backslash is the final charac‐
532       ter  on  a  line,  the next line in the file is assumed to be a logical
533       continuation of the line containing the backslash, just as in shell.
534
535       The following entry would add a --text option to the grep  command,  as
536       suggested at the beginning of this section.
537
538       grep alias --text -i -n -E -2
539
540   2. ENABLING ALIASES
541       An  application  must  enable  alias expansion for a poptContext before
542       calling poptGetNextArg() for the first time. There are three  functions
543       that define aliases for a context:
544
545
546              int poptReadDefaultConfig(poptContext con, int flags);
547              This function reads aliases from /etc/popt and the .popt file in
548              the user's home directory. Currently, flags should be  NULL,  as
549              it is provided only for future expansion.
550
551
552              int poptReadConfigFile(poptContext con, char * fn);
553              The file specified by fn is opened and parsed as a popt configu‐
554              ration file. This allows programs to use  program-specific  con‐
555              figuration files.
556
557
558              int poptAddAlias(poptContext con, struct poptAlias alias,
559                               int flags);
560              Occasionally,  processes  want to specify aliases without having
561              to read them from a configuration file. This function adds a new
562              alias  to  a  context.  The flags argument should be 0, as it is
563              currently reserved for future expansion. The new alias is speci‐
564              fied as a struct poptAlias, which is defined as:
565
566              struct poptAlias {
567                   const char * longName; /* may be NULL */
568                   char shortName; /* may be '\0' */
569                   int argc;
570                   const char ** argv; /* must be free()able */
571              };
572
573              The  first two elements, longName and shortName, specify the op‐
574              tion that is aliased. The final two, argc and argv,  define  the
575              expansion to use when the aliases option is encountered.
576

PARSING ARGUMENT STRINGS

578       Although  popt  is  usually  used for parsing arguments already divided
579       into an argv-style array, some programs need to parse strings that  are
580       formatted  identically  to command lines. To facilitate this, popt pro‐
581       vides a function that parses a string into an array of  strings,  using
582       rules similar to normal shell parsing.
583
584       #include <popt.h>
585       int poptParseArgvString(char * s, int * argcPtr,
586                               char *** argvPtr);
587       int poptDupArgv(int argc, const char ** argv, int * argcPtr,
588                               const char *** argvPtr);
589
590       The string s is parsed into an argv-style array. The integer pointed to
591       by the argcPtr parameter contains the number of  elements  parsed,  and
592       the  final  argvPtr parameter contains the address of the newly created
593       array.  The routine poptDupArgv() can be used to make a copy of an  ex‐
594       isting argument array.
595
596       The  argvPtr created by poptParseArgvString() or poptDupArgv() is suit‐
597       able to pass directly to poptGetContext().  Both routines return a sin‐
598       gle  dynamically  allocated  contiguous  block of storage and should be
599       free()ed when the application is finished with the storage.
600

HANDLING EXTRA ARGUMENTS

602       Some applications implement the equivalent of option aliasing but  need
603       to  do so through special logic. The poptStuffArgs() function allows an
604       application to insert new arguments into the current poptContext.
605
606       #include <popt.h>
607       int poptStuffArgs(poptContext con, const char ** argv);
608
609       The passed argv must have a NULL pointer as  its  final  element.  When
610       poptGetNextOpt()  is next called, the "stuffed" arguments are the first
611       to be parsed. popt returns to the normal arguments once all the stuffed
612       arguments have been exhausted.
613

EXAMPLE

615       The  following  example  is a simplified version of the program "robin"
616       which appears in Chapter 15 of the text cited below.   Robin  has  been
617       stripped  of  everything  but  its argument-parsing logic, slightly re‐
618       worked, and renamed "parse." It may prove  useful  in  illustrating  at
619       least some of the features of the extremely rich popt library.
620
621       #include <popt.h>
622       #include <stdio.h>
623       #include <stdlib.h>
624
625       void usage(poptContext optCon, int exitcode, char *error, char *addl) {
626           poptPrintUsage(optCon, stderr, 0);
627           if (error) fprintf(stderr, "%s: %s\n", error, addl);
628           exit(exitcode);
629       }
630
631       int main(int argc, char *argv[]) {
632          int     c;            /* used for argument parsing */
633          int     i = 0;        /* used for tracking options */
634          int     speed = 0;    /* used in argument parsing to set speed */
635          int     raw = 0;      /* raw mode? */
636          int     j;
637          char    buf[BUFSIZ+1];
638          const char *portname;
639          poptContext optCon;   /* context for parsing command-line options */
640
641          struct poptOption optionsTable[] = {
642             { "bps", 'b', POPT_ARG_INT, &speed, 0,
643                              "signaling rate in bits-per-second", "BPS" },
644             { "crnl", 'c', 0, 0, 'c',
645                              "expand cr characters to cr/lf sequences", NULL },
646             { "hwflow", 'h', 0, 0, 'h',
647                              "use hardware (RTS/CTS) flow control", NULL },
648             { "noflow", 'n', 0, 0, 'n',
649                              "use no flow control", NULL },
650             { "raw", 'r', 0, &raw, 0,
651                              "don't perform any character conversions", NULL },
652             { "swflow", 's', 0, 0, 's',
653                              "use software (XON/XOF) flow control", NULL } ,
654             POPT_AUTOHELP
655             { NULL, 0, 0, NULL, 0 }
656           };
657
658          optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
659          poptSetOtherOptionHelp(optCon, "[OPTIONS]* <port>");
660
661          if (argc < 2) {
662                              poptPrintUsage(optCon, stderr, 0);
663                              exit(1);
664          }
665
666          /* Now do options processing, get portname */
667          while ((c = poptGetNextOpt(optCon)) >= 0) {
668             switch (c) {
669              case 'c':
670                 buf[i++] = 'c';
671                 break;
672              case 'h':
673                 buf[i++] = 'h';
674                 break;
675              case 's':
676                 buf[i++] = 's';
677                 break;
678              case 'n':
679                 buf[i++] = 'n';
680                 break;
681             }
682          }
683          portname = poptGetArg(optCon);
684          if((portname == NULL) || !(poptPeekArg(optCon) == NULL))
685             usage(optCon, 1, "Specify a single port", ".e.g., /dev/cua0");
686
687          if (c < -1) {
688             /* an error occurred during option processing */
689             fprintf(stderr, "%s: %s\n",
690                     poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
691                     poptStrerror(c));
692             return 1;
693          }
694
695          /* Print out options, portname chosen */
696          printf("Options  chosen: ");
697          for(j = 0; j < i ; j++)
698             printf("-%c ", buf[j]);
699          if(raw) printf("-r ");
700          if(speed) printf("-b %d ", speed);
701          printf("\nPortname chosen: %s\n", portname);
702
703          poptFreeContext(optCon);
704          exit(0);
705       }
706
707       RPM,  a  popular  Linux  package management program, makes heavy use of
708       popt's features. Many of its  command-line  arguments  are  implemented
709       through  popt  aliases,  which makes RPM an excellent example of how to
710       take advantage of the popt library. For more information  on  RPM,  see
711       http://www.rpm.org.  The  popt  source  code distribution includes test
712       program(s) which use all of the features of the popt libraries in vari‐
713       ous ways. If a feature isn't working for you, the popt test code is the
714       first place to look.
715

BUGS

717       None presently known.
718

AUTHOR

720       Erik W. Troan <ewt@redhat.com>
721
722       This man page is derived in part from Linux Application Development  by
723       Michael  K.  Johnson  and  Erik W. Troan, Copyright (c) 1998 by Addison
724       Wesley Longman, Inc., and included in the popt documentation  with  the
725       permission of the Publisher and the appreciation of the Authors.
726
727       Thanks to Robert Lynch for his extensive work on this man page.
728

SEE ALSO

730       getopt(3)
731
732       Linux  Application Development, by Michael K. Johnson and Erik W. Troan
733       (Addison-Wesley, 1998; ISBN 0-201-30821-5), Chapter 24.
734
735       popt.ps is a Postscript version of the above cited book chapter. It can
736       be   found   in   the   source   archive   for   popt   available   at:
737       ftp://ftp.rpm.org/pub/rpm.
738
739
740
741                                 June 30, 1998                         POPT(3)
Impressum