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                                  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
53       array  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
63       options.  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
70       option from its arguments; either a space or  an  =  separates  a  long
71       option 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
83       options 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           int argInfo;
92           void * arg;            /* depends on argInfo */
93           int val;               /* 0 means don't return, just update flag */
94           char * descrip;        /* description for autohelp -- may be NULL */
95           char * argDescrip;     /* argument description for autohelp */
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 rest of the valid values 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      An 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      An 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
158       example,  "rm  -i -f".  POPT_ARG_VAL causes the parsing function not to
159       return 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
168       return  when  the option is encountered.  If it is 0, the parsing func‐
169       tion does not return a value, instead  parsing  the  next  command-line
170       argument.
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
176       expects, 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
211       being used, the descrip field should contain a 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
231       option does not take an argument, arg is NULL.   The  final  parameter,
232       data  is  taken  from the descrip field of the option table entry which
233       defined the callback. As descrip is a  pointer,  this  allows  callback
234       functions to be passed an arbitrary set of data (though a typecast will
235       have to 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
244       allows this by keeping all the state information for a  particular  set
245       of  command-line  arguments  in a poptContext data structure, an opaque
246       type 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                                  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
257       being 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 take one of three values:
263
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
270       A poptContext keeps track of which options have already been parsed and
271       which remain, among other things. If a program wishes to restart option
272       processing of a set of arguments, it can reset the poptContext by pass‐
273       ing the context as the sole argument to poptResetContext().
274
275       When argument processing is complete, the process should free the popt‐
276       Context  as  it  contains  dynamically  allocated components. The popt‐
277       FreeContext() function takes a poptContext as  its  sole  argument  and
278       frees the resources the context is using.
279
280       Here  are  the  prototypes  of both poptResetContext() and poptFreeCon‐
281       text():
282
283       #include <popt.h>
284       void poptFreeContext(poptContext con);
285       void poptResetContext(poptContext con);
286
287
288   3. PARSING THE COMMAND LINE
289       After an application has created a poptContext, it  may  begin  parsing
290       arguments. poptGetNextOpt() performs the actual argument parsing.
291
292       #include <popt.h>
293       int poptGetNextOpt(poptContext con);
294
295       Taking  the context as its sole argument, this function parses the next
296       command-line argument found. After finding the  next  argument  in  the
297       option table, the function fills in the object pointed to by the option
298       table entry's arg pointer if it is not NULL. If the val entry  for  the
299       option is non-0, the function then returns that value. Otherwise, popt‐
300       GetNextOpt() continues on to the next argument.
301
302       poptGetNextOpt() returns -1 when the final argument  has  been  parsed,
303       and  other negative values when errors occur. This makes it a good idea
304       to keep the val elements in the options table greater than 0.
305
306       If all of the command-line options are handled  through  arg  pointers,
307       command-line parsing is reduced to the following line of code:
308
309       rc = poptGetNextOpt(poptcon);
310
311       Many  applications require more complex command-line parsing than this,
312       however, and use the following structure:
313
314       while ((rc = poptGetNextOpt(poptcon)) > 0) {
315            switch (rc) {
316                 /* specific arguments are handled here */
317            }
318       }
319
320       When returned options are handled, the application needs  to  know  the
321       value  of any arguments that were specified after the option. There are
322       two ways to discover them. One is to ask popt to  fill  in  a  variable
323       with  the  value of the option through the option table's arg elements.
324       The other is to use poptGetOptArg():
325
326       #include <popt.h>
327       char * poptGetOptArg(poptContext con);
328
329       This function returns the argument given for the final option  returned
330       by  poptGetNextOpt(),  or it returns NULL if no argument was specified.
331       The calling function is responsible for deallocating this string.
332
333
334   4. LEFTOVER ARGUMENTS
335       Many applications take an arbitrary number of  command-line  arguments,
336       such  as  a  list  of file names. When popt encounters an argument that
337       does not begin with a -, it assumes it is such an argument and adds  it
338       to  a list of leftover arguments. Three functions allow applications to
339       access such arguments:
340
341       const char * poptGetArg(poptContext con);
342              This function returns the next leftover argument and marks it as
343              processed.
344
345       const char * poptPeekArg(poptContext con);
346              The  next  leftover  argument is returned but not marked as pro‐
347              cessed.  This allows an application to look ahead into the argu‐
348              ment list, without modifying the list.
349
350       const char ** poptGetArgs(poptContext con);
351              All the leftover arguments are returned in a manner identical to
352              argv.  The final element in the returned array points  to  NULL,
353              indicating the end of the arguments.
354
355
356   5. AUTOMATIC HELP MESSAGES
357       The  popt  library  can  automatically  generate  help  messages  which
358       describe the options a program accepts. There are  two  types  of  help
359       messages  which  can  be generated. Usage messages are a short messages
360       which lists valid options, but does not describe  them.  Help  messages
361       describe each option on one (or more) lines, resulting in a longer, but
362       more useful, message. Whenever automatic help messages  are  used,  the
363       descrip  and  argDescrip  fields  struct  poptOption  members should be
364       filled in for each option.
365
366       The POPT_AUTOHELP macro makes it easy to add --usage  and  --help  mes‐
367       sages  to your program, and is described in part 1 of this man page. If
368       more control is needed over your help messages, the following two func‐
369       tions are available:
370
371       #include <popt.h>
372       void poptPrintHelp(poptContext con, FILE * f, int flags);
373       void poptPrintUsage(poptContext con, FILE * f, int flags);
374
375       poptPrintHelp()  displays  the  standard help message to the stdio file
376       descriptor f, while poptPrintUsage() displays the  shorter  usage  mes‐
377       sage.  Both  functions currently ignore the flags argument; it is there
378       to allow future changes.
379
380

ERROR HANDLING

382       All of the popt functions that can return errors return integers.  When
383       an error occurs, a negative error code is returned. The following table
384       summarizes the error codes that occur:
385
386            Error                      Description
387       POPT_ERROR_NOARG       Argument missing for an option.
388       POPT_ERROR_BADOPT      Option's argument couldn't be parsed.
389       POPT_ERROR_OPTSTOODEEP Option aliasing nested too deeply.
390       POPT_ERROR_BADQUOTE    Quotations do not match.
391       POPT_ERROR_BADNUMBER   Option couldn't be converted to number.
392       POPT_ERROR_OVERFLOW    A given number was too big or small.
393
394       Here is a more detailed discussion of each error:
395
396
397       POPT_ERROR_NOARG
398              An option that requires an argument was specified on the command
399              line,  but  no  argument was given. This can be returned only by
400              poptGetNextOpt().
401
402
403       POPT_ERROR_BADOPT
404              An option was specified in argv but is not in the option  table.
405              This error can be returned only from poptGetNextOpt().
406
407
408       POPT_ERROR_OPTSTOODEEP
409              A  set  of  option aliases is nested too deeply. Currently, popt
410              follows options only 10 levels to  prevent  infinite  recursion.
411              Only poptGetNextOpt() can return this error.
412
413
414       POPT_ERROR_BADQUOTE
415              A  parsed string has a quotation mismatch (such as a single quo‐
416              tation mark).  poptParseArgvString(),  poptReadConfigFile(),  or
417              poptReadDefaultConfig() can return this error.
418
419
420       POPT_ERROR_BADNUMBER
421              A  conversion from a string to a number (int or long) failed due
422              to the string containing  non-numeric  characters.  This  occurs
423              when   poptGetNextOpt()   is  processing  an  argument  of  type
424              POPT_ARG_INT, POPT_ARG_SHORT, POPT_ARG_LONG,  POPT_ARG_LONGLONG,
425              POPT_ARG_FLOAT, or POPT_ARG_DOUBLE.
426
427
428       POPT_ERROR_OVERFLOW
429              A  string-to-number conversion failed because the number was too
430              large or too small. Like POPT_ERROR_BADNUMBER,  this  error  can
431              occur  only  when  poptGetNextOpt() is processing an argument of
432              type POPT_ARG_INT, POPT_ARG_SHORT, POPT_ARG_LONG, POPT_ARG_LONG‐
433              LONG, POPT_ARG_FLOAT, or POPT_ARG_DOUBLE.
434
435
436       POPT_ERROR_ERRNO
437              A  system  call returned with an error, and errno still contains
438              the error from the system call.  Both  poptReadConfigFile()  and
439              poptReadDefaultConfig() can return this error.
440
441
442       Two functions are available to make it easy for applications to provide
443       good error messages.
444
445
446              const char *const poptStrerror(const int error);
447              This function takes a popt  error  code  and  returns  a  string
448              describing the error, just as with the standard strerror() func‐
449              tion.
450
451
452              const char * poptBadOption(poptContext con, int flags);
453              If an error  occurred  during  poptGetNextOpt(),  this  function
454              returns  the option that caused the error. If the flags argument
455              is  set  to  POPT_BADOPTION_NOALIAS,  the  outermost  option  is
456              returned.  Otherwise,  flags should be 0, and the option that is
457              returned may have been specified through an alias.
458
459       These two functions make popt error handling trivial for most  applica‐
460       tions.  When  an error is detected from most of the functions, an error
461       message is printed along with the  error  string  from  poptStrerror().
462       When  an error occurs during argument parsing, code similar to the fol‐
463       lowing displays a useful error message:
464
465       fprintf(stderr, "%s: %s\n",
466               poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
467               poptStrerror(rc));
468
469

OPTION ALIASING

471       One of the primary benefits of using popt over getopt() is the  ability
472       to  use  option  aliasing. This lets the user specify options that popt
473       expands into other options when they are  specified.  If  the  standard
474       grep  program  made  use  of popt, users could add a --text option that
475       expanded to -i -n -E -2 to let them more  easily  find  information  in
476       text files.
477
478
479   1. SPECIFYING ALIASES
480       Aliases  are  normally specified in two places: /etc/popt and the .popt
481       file in the user's home directory (found through the  HOME  environment
482       variable).  Both  files  have  the  same format, an arbitrary number of
483       lines formatted like this:
484
485       appname alias newoption expansion
486
487       The appname is the name of the application, which must be the  same  as
488       the name parameter passed to poptGetContext(). This allows each file to
489       specify aliases for multiple programs. The alias keyword specifies that
490       an  alias  is being defined; currently popt configuration files support
491       only aliases, but other abilities may be added in the future. The  next
492       option  is  the  option  that should be aliased, and it may be either a
493       short or a long option. The rest of the line  specifies  the  expansion
494       for  the alias. It is parsed similarly to a shell command, which allows
495       \, ", and ' to be used for quoting. If a backslash is the final charac‐
496       ter  on  a  line,  the next line in the file is assumed to be a logical
497       continuation of the line containing the backslash, just as in shell.
498
499       The following entry would add a --text option to the grep  command,  as
500       suggested at the beginning of this section.
501
502       grep alias --text -i -n -E -2
503
504   2. ENABLING ALIASES
505       An  application  must  enable  alias expansion for a poptContext before
506       calling poptGetNextArg() for the first time. There are three  functions
507       that define aliases for a context:
508
509
510              int poptReadDefaultConfig(poptContext con, int flags);
511              This function reads aliases from /etc/popt and the .popt file in
512              the user's home directory. Currently, flags should be  NULL,  as
513              it is provided only for future expansion.
514
515
516              int poptReadConfigFile(poptContext con, char * fn);
517              The file specified by fn is opened and parsed as a popt configu‐
518              ration file. This allows programs to use  program-specific  con‐
519              figuration files.
520
521
522              int poptAddAlias(poptContext con, struct poptAlias alias,
523                               int flags);
524              Occasionally,  processes  want to specify aliases without having
525              to read them from a configuration file. This function adds a new
526              alias  to  a  context.  The flags argument should be 0, as it is
527              currently reserved for future expansion. The new alias is speci‐
528              fied as a struct poptAlias, which is defined as:
529
530              struct poptAlias {
531                   const char * longName; /* may be NULL */
532                   char shortName; /* may be '\0' */
533                   int argc;
534                   const char ** argv; /* must be free()able */
535              };
536
537              The  first  two  elements,  longName  and shortName, specify the
538              option that is aliased. The final two, argc and argv, define the
539              expansion to use when the aliases option is encountered.
540

PARSING ARGUMENT STRINGS

542       Although  popt  is  usually  used for parsing arguments already divided
543       into an argv-style array, some programs need to parse strings that  are
544       formatted  identically  to command lines. To facilitate this, popt pro‐
545       vides a function that parses a string into an array of  strings,  using
546       rules similar to normal shell parsing.
547
548       #include <popt.h>
549       int poptParseArgvString(char * s, int * argcPtr,
550                               char *** argvPtr);
551       int poptDupArgv(int argc, const char ** argv, int * argcPtr,
552                               const char *** argvPtr);
553
554       The string s is parsed into an argv-style array. The integer pointed to
555       by the argcPtr parameter contains the number of  elements  parsed,  and
556       the  final  argvPtr parameter contains the address of the newly created
557       array.  The routine poptDupArgv() can be used to  make  a  copy  of  an
558       existing argument array.
559
560       The  argvPtr created by poptParseArgvString() or poptDupArgv() is suit‐
561       able to pass directly to poptGetContext().  Both routines return a sin‐
562       gle  dynamically  allocated  contiguous  block of storage and should be
563       free()ed when the application is finished with the storage.
564

HANDLING EXTRA ARGUMENTS

566       Some applications implement the equivalent of option aliasing but  need
567       to  do so through special logic. The poptStuffArgs() function allows an
568       application to insert new arguments into the current poptContext.
569
570       #include <popt.h>
571       int poptStuffArgs(poptContext con, const char ** argv);
572
573       The passed argv must have a NULL pointer as  its  final  element.  When
574       poptGetNextOpt()  is next called, the "stuffed" arguments are the first
575       to be parsed. popt returns to the normal arguments once all the stuffed
576       arguments have been exhausted.
577

EXAMPLE

579       The  following  example  is a simplified version of the program "robin"
580       which appears in Chapter 15 of the text cited below.   Robin  has  been
581       stripped   of  everything  but  its  argument-parsing  logic,  slightly
582       reworked, and renamed "parse." It may prove useful in  illustrating  at
583       least some of the features of the extremely rich popt library.
584
585       #include <popt.h>
586       #include <stdio.h>
587
588       void usage(poptContext optCon, int exitcode, char *error, char *addl) {
589           poptPrintUsage(optCon, stderr, 0);
590           if (error) fprintf(stderr, "%s: %s0, error, addl);
591           exit(exitcode);
592       }
593
594       int main(int argc, char *argv[]) {
595          char    c;            /* used for argument parsing */
596          int     i = 0;        /* used for tracking options */
597          char    *portname;
598          int     speed = 0;    /* used in argument parsing to set speed */
599          int     raw = 0;      /* raw mode? */
600          int     j;
601          char    buf[BUFSIZ+1];
602          poptContext optCon;   /* context for parsing command-line options */
603
604          struct poptOption optionsTable[] = {
605             { "bps", 'b', POPT_ARG_INT, &speed, 0,
606                                 "signaling rate in bits-per-second", "BPS" },
607             { "crnl", 'c', 0, 0, 'c',
608                                 "expand cr characters to cr/lf sequences", NULL },
609             { "hwflow", 'h', 0, 0, 'h',
610                                 "use hardware (RTS/CTS) flow control", NULL },
611             { "noflow", 'n', 0, 0, 'n',
612                                 "use no flow control", NULL },
613             { "raw", 'r', 0, &raw, 0,
614                                 "don't perform any character conversions", NULL },
615             { "swflow", 's', 0, 0, 's',
616                                 "use software (XON/XOF) flow control", NULL } ,
617             POPT_AUTOHELP
618             { NULL, 0, 0, NULL, 0 }
619           };
620
621          optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
622          poptSetOtherOptionHelp(optCon, "[OPTIONS]* <port>");
623
624          if (argc < 2) {
625                                 poptPrintUsage(optCon, stderr, 0);
626                                 exit(1);
627          }
628
629          /* Now do options processing, get portname */
630          while ((c = poptGetNextOpt(optCon)) >= 0) {
631             switch (c) {
632              case 'c':
633                 buf[i++] = 'c';
634                 break;
635              case 'h':
636                 buf[i++] = 'h';
637                 break;
638              case 's':
639                 buf[i++] = 's';
640                 break;
641              case 'n':
642                 buf[i++] = 'n';
643                 break;
644             }
645          }
646          portname = poptGetArg(optCon);
647          if((portname == NULL) || !(poptPeekArg(optCon) == NULL))
648             usage(optCon, 1, "Specify a single port", ".e.g., /dev/cua0");
649
650          if (c < -1) {
651             /* an error occurred during option processing */
652             fprintf(stderr, "%s: %s\n",
653                     poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
654                     poptStrerror(c));
655             return 1;
656          }
657
658          /* Print out options, portname chosen */
659          printf("Options  chosen: ");
660          for(j = 0; j < i ; j++)
661             printf("-%c ", buf[j]);
662          if(raw) printf("-r ");
663          if(speed) printf("-b %d ", speed);
664          printf("\nPortname chosen: %s\n", portname);
665
666          poptFreeContext(optCon);
667          exit(0);
668       }
669
670       RPM,  a  popular  Linux  package management program, makes heavy use of
671       popt's features. Many of its  command-line  arguments  are  implemented
672       through  popt  aliases,  which makes RPM an excellent example of how to
673       take advantage of the popt library. For more information  on  RPM,  see
674       http://www.rpm.org.  The  popt  source  code distribution includes test
675       program(s) which use all of the features of the popt libraries in vari‐
676       ous ways. If a feature isn't working for you, the popt test code is the
677       first place to look.
678

BUGS

680       None presently known.
681

AUTHOR

683       Erik W. Troan <ewt@redhat.com>
684
685       This man page is derived in part from Linux Application Development  by
686       Michael  K.  Johnson  and  Erik W. Troan, Copyright (c) 1998 by Addison
687       Wesley Longman, Inc., and included in the popt documentation  with  the
688       permission of the Publisher and the appreciation of the Authors.
689
690       Thanks to Robert Lynch for his extensive work on this man page.
691

SEE ALSO

693       getopt(3)
694
695       Linux  Application Development, by Michael K. Johnson and Erik W. Troan
696       (Addison-Wesley, 1998; ISBN 0-201-30821-5), Chapter 24.
697
698       popt.ps is a Postscript version of the above cited book chapter. It can
699       be   found   in   the   source   archive   for   popt   available   at:
700       ftp://ftp.rpm.org/pub/rpm.
701
702
703
704                                 June 30, 1998                         POPT(3)
Impressum