C Library Functions libpopt(3)
NAME
libpopt - parse command-line options
SYNOPSIS
#include
poptContext poptGetContext(const char * name, int argc,
const char ** argv,
const struct poptOption * options,
int flags);
void poptFreeContext(poptContext con);
void poptResetContext(poptContext con);
int poptGetNextOpt(poptContext con);
const char * poptGetOptArg(poptContext con);
const char * poptGetArg(poptContext con);
const char * poptPeekArg(poptContext con);
const char ** poptGetArgs(poptContext con);
const char *const poptStrerror(const int error);
const char * poptBadOption(poptContext con, int flags);
int poptReadDefaultConfig(poptContext con, int flags);
int poptReadConfigFile(poptContext con, char * fn);
int poptAddAlias(poptContext con, struct poptAlias alias,
int flags);
int poptParseArgvString(char * s, int * argcPtr,
const char *** argvPtr);
int poptDupArgv(int argc, const char ** argv, int * argcPtr,
const char *** argvPtr);
int poptStuffArgs(poptContext con, const char ** argv);
DESCRIPTION
The popt library parses command-line options. The popt
library provides an alternative to parsing the argv array by
hand, or using the getopt(3) functions getopt() and
getoptlong().
SunOS 5.11 Last change: 31 May 2004 1
C Library Functions libpopt(3)
The popt library has the following advantages:
]o popt does not use global variables, thus enabling mul-
tiple passes in parsing argv.
]o popt can parse an arbitrary array of argv-style ele-
ments, allowing parsing of command-line strings from
any source.
]o popt provides a standard method of option aliasing.
This feature is discussed in detail below.
]o popt can exec external option filters.
]o popt can automatically generate help and usage messages
for the application.
The popt library supports short and long options. A short
option consists of a hyphen followed by a single
alphanumeric character. A long option, common in GNU utili-
ties, consists of two hyphens followed by a string composed
of letters, numbers, and hyphens. Long options can option-
ally begin with a single hyphen, primarily to allow
command-line compatibility between popt applications and X
toolkit applications. Either type of option can be followed
by an argument. A space separates a short option from its
argument. Either a space or an equals sign separates a long
option from an argument.
The popt library is highly portable and should work on any
POSIX platform. The latest version is distributed with rpm
and is available from: ftp:/ftp.rpm.org/pub/rpm/dist.
The popt library may be redistributed under the X consortium
license, see the file COPYING in the popt source distribu-
tion for details.
EXTENDED DESCRIPTION
Option Tables
Each application provides popt with information about the
command-line options for the application, by means of an
option table. An option table is an array of struct poptOp-
tion structures, with the following format:
#include
struct poptOption {
const char * longName; /* may be NUL */
char shortName; /* may be ' ' */
int argInfo;
void * arg; /* depends on argInfo */
SunOS 5.11 Last change: 31 May 2004 2
C Library Functions libpopt(3)
int val; /* 0 means do not return, just update flag */
char * descrip; /* description for autohelp -- may be NUL */
char * argDescrip; /* argument description for autohelp */
};
Option Table Members
Each member of the table defines a single option that may be
passed to the program. Long and short options are considered
to be a single option that can occur in two different forms.
The option table members are as follows:
longName Defines the name of the option in a
long name.
shortName Defines the name of the option in a
single character.
argInfo Tells popt what type of argument is
expected after the option. Valid
values are as follows:
POPTARGDOUBLE Double argument
expected, arg type:
double
POPTARGFLOAT Float argument
expected, arg type:
float
POPTARGINT Integer argument
expected, arg type:
int
POPTARGLONG Long integer
expected, arg type:
long
SunOS 5.11 Last change: 31 May 2004 3
C Library Functions libpopt(3)
POPTARGNONE No argument
expected, arg type:
int
POPTARGSTRING No type checking to
be performed, arg
type: char *
POPTARGVAL Integer value taken
from val, arg type:
int
For numeric values, if the argInfo
value is bitwise or'd with one of
POPTARGFLAGOR, POPTARGFLAGAND,
or POPTARGFLAGXOR, the value is
saved by performing an OR, AND, or
XOR. If the argInfo value is bitwise
or'd with POPTARGFLAGNOT, the
value is negated before saving. For
the common operations of setting or
clearing bits, POPTBITSET and
POPTBITCLR have the appropriate
flags set to perform bit operations.
If the argInfovalue is bitwise or'd
with POPTARGFLAGONEDASH, the long
argument may be given with a single
hyphen instead of two. For example,
if --longopt is an option with
POPTARGFLAGONEDASH, -longopt is
also accepted.
arg Allows popt to automatically update
program variables. If arg is NUL,
popt ignores arg and takes no spe-
cial action. Otherwise, arg points
to a variable of the appropriate
type, as follows:
]o If argInfo is POPTARGNONE,
the variable pointed to by arg
is set to 1 when the option is
used.
]o
SunOS 5.11 Last change: 31 May 2004 4
C Library Functions libpopt(3)
If the option takes an argu-
ment, the variable pointed to
by arg is updated to reflect
the value of the argument. Any
string is acceptable for
POPTARGSTRING arguments.
POPTARGINT, POPTARGLONG,
POPTARGFLOAT, and
POPTARGDOUBLE arguments are
converted to the appropriate
type, and an error returned if
the conversion fails.
POPTARGVAL causes arg to be set to
the integer value of val when the
argument is found. This is useful
for mutually-exclusive arguments in
cases where it is not an error for
multiple arguments to occur and
where you want the last argument
specified to take precedence, for
example, rm -i -f. POPTARGVAL
causes the parsing function not to
return a value, because the value of
val has already been used.
If the argInfo value is bitwise or'd
with POPTARGFLAGOPTIONAL, the
argument to the long option may be
omitted. If the long option is used
without an argument, a default value
of zero or NUL is saved if the arg
pointer is present. Otherwise, the
behavior is identical to that of a
long option with an argument.
val The value returned by the popt pars-
ing function when the option is
encountered. If val is 0, the pars-
ing function does not return a
value. Instead, popt parses the next
command-line argument.
descrip Text description of the argument.
Only required if automatic help mes-
sages are desired. Automatic usage
messages can be generated without
SunOS 5.11 Last change: 31 May 2004 5
C Library Functions libpopt(3)
this argument.
argDescrip Short summary of the type of argu-
ments expected by the option, or
NUL if the option does not require
any arguments. Only required if
automatic help messages are desired.
Automatic usage messages can be gen-
erated without this argument.
The final structure in the table should have all pointer
values set to NUL and all arithmetic values set to 0, mark-
ing the end of the table. The macro POPTABLEND performs
these tasks.
Help and Usage Output
If popt should automatically provide --usage and --help
options, one line in the option table should contain the
macro POPTAUTOHELP. This macro includes another option
table, via POPTARGINCLUDETABLE, which provides the table
entries for these arguments. When the --usage or --help
option is passed to applications that use popt automatic
help, popt displays the appropriate message on stderr, and
exits the application with a return code of 0. To use popt
automatic help generation in a different way, you must
explicitly add the option entries to the application's
option table, instead of using POPTAUTOHELP.
If the argInfo value is bitwise or'd with
POPTARGFLAGDOCHIDEN, the argument is not shown in help
output.
If the argInfo value is bitwise or'd with
POPTARGFLAGSHOWDEFAULT, the inital value of the arg is
shown in help output.
Special Option Table Entries
Two types of option table entries do not specify command-
line options. When either of these types of entries is
used, the longName element must be NUL and the shortName
element must be \0.
The first of these special entry types allows the applica-
tion to nest another option table in the current option
table. Such nesting may extend quite deeply, the actual
depth is limited by the application stack. Including other
option tables allows a library to provide a standard set of
command-line options to every application that uses the
SunOS 5.11 Last change: 31 May 2004 6
C Library Functions libpopt(3)
library. This is often done in graphical programming toolk-
its, for example. To nest another option table, set the
argInfo field to POPTARGINCLUDETABLE and the arg field to
point to the table that is being included. If automatic help
generation is used, the descrip field should contain an
overall description of the option table being included.
The other special option table entry type tells popt to call
a function when any option in that table is found. This
callback functionality is especially useful when included
option tables are used, because the application that pro-
vides the top-level option table does not need to be aware
of the other options that are provided by the included
table. When a callback is set for a table, the parsing func-
tion never returns information on an option in the table.
Instead, option information must be retained via the call-
back or by having popt set a variable through the option's
arg field. Option callbacks should match the following pro-
totype:
void poptCallbackType(poptContext con,
const struct poptOption * opt,
const char * arg, void * data);
The callback uses the following parameters:
con The context that is being parsed. See the
next section for information on contexts.
opt The option that triggered this callback.
arg The argument for the opt option. If the
option does not take an argument, arg is
NUL.
data Taken from the descrip field of the option
table entry that defined the callback. As
descrip is a pointer, this allows you to
pass an arbitrary set of data to callback
functions, though a typecast must be used.
The option table entry that defines a callback has an
argInfo of POPTARGCALBACK, an arg that points to the
SunOS 5.11 Last change: 31 May 2004 7
C Library Functions libpopt(3)
callback function, and a descrip field that specifies an
arbitrary pointer to be passed to the callback.
Creating a Context
popt can interleave the parsing of multiple command-line
sets. popt allows this by keeping all of the state informa-
tion for a particular set of command-line arguments in a
poptContext data structure, an opaque type that should not
be modified outside the popt library.
New popt contexts are created by poptGetContext():
poptContext poptGetContext(const char * name, int argc,
const char ** argv,
const struct poptOption * options,
int flags);
The poptGetContext() function takes the following parame-
ters:
name Used only for alias handling. name
should be the name of the applica-
tion whose options are being parsed,
or should be NUL if no option
aliasing is desired.
argc, argv Specifies the command-line arguments
to parse. These arguments are gen-
erally passed to poptGetContext()
exactly as they were passed to the
application's main() function.
options Points to the table of command-line
options. See the Option Tables sec-
tion above.
flags Can take one of the following
values:
POPTCONTEXTNOEXEC Ignore exec
expansions
SunOS 5.11 Last change: 31 May 2004 8
C Library Functions libpopt(3)
POPTCONTEXTKEPFIRST Do not
ignore
argv[0]
POPTCONTEXTPOSIXMEHARDEORptions can-
not follow
arguments
A poptContext keeps track of which options have already been
parsed and which remain to be parsed. If an application
wishes to restart processing the options of a set of argu-
ments, the application can reset the poptContext by passing
the context as the sole argument to poptResetContext().
When argument processing is complete, the process should
free the poptContext, as it contains dynamically allocated
components. The poptFreeContext() function takes a poptCon-
text as its sole argument and frees the resources that the
context is using.
Here are the prototypes of both poptResetContext() and
poptFreeContext():
#include
void poptFreeContext(poptContext con);
void poptResetContext(poptContext con);
Parsing the Command Line
After an application has created a poptContext, the poptCon-
text may begin parsing arguments. poptGetNextOpt() performs
the actual argument parsing:
#include
int poptGetNextOpt(poptContext con);
Taking the context as its sole argument, the poptGetNex-
tOpt() function parses the next command-line argument found.
When poptGetNextOpt() finds the next argument in the option
table, the function populates the object pointed to by the
option table entry's arg pointer, if the pointer is not
NUL. If the val entry for the option is not zero, the func-
tion returns that value. Otherwise, poptGetNextOpt() contin-
ues to the next argument.
poptGetNextOpt() returns -1 when the final argument has been
parsed, and other negative values when errors occur.
SunOS 5.11 Last change: 31 May 2004 9
C Library Functions libpopt(3)
Therefore, you should ensure that the val elements in the
option table are greater than 0.
If all of the command-line options are handled through arg
pointers, command-line parsing is reduced to the following
line of code:
rc = poptGetNextOpt(poptcon);
Many applications require more complex command-line parsing
than this, however, and use the following structure:
while ((rc = poptGetNextOpt(poptcon)) > 0) {
switch (rc) {
/* specific arguments are handled here */
}
}
When returned options are handled, the application needs to
know the value of any arguments that were specified after
the option. There are two ways to discover these values:
]o Ask popt to populate a variable with the value of the
option from the option table's arg elements.
]o Use poptGetOptArg():
#include
const char * poptGetOptArg(poptContext con);
The poptGetOptArg() function returns the argument given for
the final option returned by poptGetNextOpt(), or returns
NUL if no argument was specified.
Leftover Arguments
Many applications take an arbitrary number of command-line
arguments, such as a list of file names. When popt
encounters an argument that does not begin with a hyphen,
popt assumes that this is such an argument, and adds the
argument to a list of leftover arguments. Three functions
allow applications to access such arguments:
const char * poptGetArg(poptContext con);
Returns the next leftover argument and marks the argu-
ment as processed.
SunOS 5.11 Last change: 31 May 2004 10
C Library Functions libpopt(3)
const char * poptPeekArg(poptContext con);
Returns the next leftover argument but does not mark the
argument as processed. This allows an application to
look ahead into the argument list, without modifying the
list.
const char ** poptGetArgs(poptContext con);
Returns all of the leftover arguments in a manner ident-
ical to argv. The final element in the returned array
points to NUL, indicating the end of the arguments.
Automatic Help Messages
The popt library can automatically generate help messages
that describe the options that an application accepts. Two
types of help messages can be generated:
]o Usage messages are short messages that list valid
options, but do not describe the options.
]o Help messages describe each option in one or more
lines, resulting in a longer but more useful message.
Whenever automatic help messages are used, the descrip and
argDescrip members of the struct poptOption structure should
be populated for each option.
The POPTAUTOHELP macro makes it easy to add usage and help
messages to your application, as described earlier in this
man page. If you need more control over your help messages,
use the following functions:
#include
void poptPrintHelp(poptContext con, FILE * f, int flags);
void poptPrintUsage(poptContext con, FILE * f, int flags);
poptPrintHelp() displays the standard help message to the
stdio file descriptor f, while poptPrintUsage() displays the
shorter usage message. Both functions currently ignore the
flags argument, which is provided for future functionality.
Option Aliasing
One of the primary benefits of popt is the ability to use
option aliasing. Option aliasing allows the user to specify
options that popt expands into other options. For example.
SunOS 5.11 Last change: 31 May 2004 11
C Library Functions libpopt(3)
if the standard grep command made use of popt, users could
add a --text option that expanded to -i -n -E -2, to allow
users to more easily find information in text files.
Specifying Aliases
Aliases are normally specified in two places:
]o /etc/popt
]o $HOME/.popt
Both files have the same format, that is, an arbitrary
number of lines formatted as follows:
appname alias newoption expansion
An alias specification is composed of the following ele-
ments:
appname Specifies the name of the applica-
tion, which must be the same as the
name parameter passed to poptGetCon-
text(). This allows each file to
specify aliases for multiple pro-
grams.
alias Specifies that an alias is being
defined. Currently, popt configura-
tion files support only aliases, but
other abilities may be added in the
future.
newoption Specifies the option that should be
aliased, either a short option or a
long option.
expansion Specifies the expansion for the
alias. The expansion is parsed in a
similar way to a shell command:
backslashes are allowed, and single
quotation marks can be used for
quoting. If a backslash is the final
character on a line, the next line
in the file is assumed to be a logi-
cal continuation of the line
SunOS 5.11 Last change: 31 May 2004 12
C Library Functions libpopt(3)
containing the backslash, just as in
a shell command.
For example, the following entry would add to the grep com-
mand the --text option described earlier:
grep alias --text -i -n -E -2
Enabling Aliases
An application must enable alias expansion for a poptCon-
text, before calling poptGetNextArg() for the first time.
Three functions define aliases for a context:
int poptReadDefaultConfig(poptContext con, int flags);
Reads aliases from /etc/popt and $HOME/.popt. The flags
argument should be NUL, it is provided only for future
expansion.
int poptReadConfigFile(poptContext con, char * fn);
Opens the file specified by fn and parses the file as a
popt configuration file. This allows applications to use
application-specific configuration files.
int poptAddAlias(poptContext con, struct poptAlias alias,
int flags);
Adds a new alias to a context. This function is useful
when processes want to specify aliases without having to
read them from a configuration file. The flags argument
should be 0, it is provided only for future expansion.
The new alias is specified as a struct poptAlias, which
is defined as follows:
struct poptAlias {
const char * longName; /* may be NUL */
char shortName; /* may be ' ' */
int argc;
const char ** argv; /* must be free()able */
};
longName and shortName specify the option that is
aliased. argc and argv define the expansion to use when
SunOS 5.11 Last change: 31 May 2004 13
C Library Functions libpopt(3)
the aliases option is encountered.
Parsing Argument Strings
popt usually parses arguments that are already divided into
an argv-style array. However, some applications need to
parse strings that are formatted identically to command
lines. To facilitate this, popt provides a function that
parses a string into an array of strings, using rules simi-
lar to those of normal shell parsing:
#include
int poptParseArgvString(char * s, int * argcPtr,
char *** argvPtr);
int poptDupArgv(int argc, const char ** argv, int * argcPtr,
const char *** argvPtr);
The string s is parsed into an argv-style array. The integer
pointed to by the argcPtr parameter contains the number of
elements parsed, and the final argvPtr parameter contains
the address of the newly created array. The routine poptDu-
pArgv() can be used to make a copy of an existing argument
array.
The argvPtr created by poptParseArgvString() or poptDu-
pArgv() can be passed directly to poptGetContext(). Both
routines return a single dynamically allocated contiguous
block of storage and should be freed using free() when the
application is finished with the storage.
Handling Extra Arguments
Some applications implement the equivalent of option alias-
ing but do so using special logic. The poptStuffArgs() func-
tion allows an application to insert new arguments into the
current poptContext:
#include
int poptStuffArgs(poptContext con, const char ** argv);
The passed argv must have a NUL pointer as its final ele-
ment. When poptGetNextOpt() is next called, the "stuffed"
arguments are the first to be parsed. popt returns to the
normal arguments when all of the stuffed arguments have been
exhausted.
ERORS
All of the popt functions that can return errors return
integers. When an error occurs, a negative error code is
returned. The following error codes can occur:
SunOS 5.11 Last change: 31 May 2004 14
C Library Functions libpopt(3)
POPTERORBADNUMBER A string-to-number conversion failed
because the string contains non-
numeric characters. This occurs when
poptGetNextOpt() is processing an
argument of type POPTARGINT,
POPTARGLONG, POPTARGFLOAT, or
POPTARGDOUBLE.
POPTERORBADOPT An option was specified in argv but
is not in the option table. This
error can be returned only from
poptGetNextOpt().
POPTERORBADQUOTE A parsed string has a quotation
mismatch, for example, a single quo-
tation mark. poptParseArgvString(),
poptReadConfigFile(), or poptReadDe-
faultConfig() can return this error.
POPTERORERNO A system call returned with an
error, and errno still contains the
error from the system call. Both
poptReadConfigFile() and poptReadDe-
faultConfig() can return this error.
POPTERORNOARG An option that requires an argument
was specified on the command line,
but no argument was given. This
error can be returned only by
poptGetNextOpt().
POPTEROROPTSTODEP A set of option aliases is nested
too deeply. Currently, popt follows
options to only 10 levels, to
prevent infinite recursion. Only
poptGetNextOpt() can return this
error.
POPTEROROVERFLOW A string-to-number conversion failed
because the number is too large or
SunOS 5.11 Last change: 31 May 2004 15
C Library Functions libpopt(3)
too small. This error can occur only
when poptGetNextOpt() is processing
an argument of type POPTARGINT,
POPTARGLONG, POPTARGFLOAT, or
POPTARGDOUBLE.
Two functions allow applications to provide good error mes-
sages:
const char *const poptStrerror(const int error);
Takes a popt error code and returns a string describing
the error, just as with the standard strerror() func-
tion.
const char * poptBadOption(poptContext con, int flags);
Returns the option that caused the error, if an error
occurred during poptGetNextOpt(). If the flags argument
is set to POPTBADOPTIONOALIAS, the outermost option
is returned. Otherwise, flags should be 0, and the
option that is returned may have been specified through
an alias.
These two functions ensure that popt error handling is
trivial for most applications. When an error is detected
from most of the functions, an error message is printed
along with the error string from poptStrerror(). When an
error occurs during argument parsing, code similar to the
following displays a useful error message:
fprintf(stderr, "%s: %s0,
poptBadOption(optCon, POPTBADOPTIONOALIAS),
poptStrerror(rc));
EXAMPLES
Example 1: Parse Program Created From robin Program
The following example is a simplified version of the robin
program that appears in Chapter 15 of "Linux Application
Development" by Michael K. Johnson and Erik W. Troan (copy-
right 1998 by Addison Wesley Longman, Inc.). The robin pro-
gram has been stripped of everything but its argument-
parsing logic, slightly reworked, and renamed parse. This
program illustrates some of the features of the extremely
SunOS 5.11 Last change: 31 May 2004 16
C Library Functions libpopt(3)
rich popt library.
#include
#include
void usage(poptContext optCon, int exitcode, char *error, char *addl) {
poptPrintUsage(optCon, stderr, 0);
if (error) fprintf(stderr, "%s: %s0, error, addl);
exit(exitcode);
}
int main(int argc, char *argv[]) {
char c; /* used for argument parsing */
int i = 0; /* used for tracking options */
char *portname;
int speed = 0; /* used in argument parsing to set speed */
int raw = 0; /* raw mode? */
int j;
char buf[BUFSIZ]1];
poptContext optCon; /* context for parsing command-line options */
struct poptOption optionsTable[] = {
{ "bps", 'b', POPTARGINT, &speed, 0,
"signaling rate in bits-per-second", "BPS" },
{ "crnl", 'c', 0, 0, 'c',
"expand cr characters to cr/lf sequences" },
{ "hwflow", 'h', 0, 0, 'h',
"use hardware (RTS/CTS) flow control" },
{ "noflow", 'n', 0, 0, 'n',
"use no flow control" },
{ "raw", 'r', 0, &raw, 0,
"don't perform any character conversions" },
{ "swflow", 's', 0, 0, 's',
"use software (XON/XOF) flow control" } ,
POPTAUTOHELP
{ NUL, 0, 0, NUL, 0 }
};
optCon = poptGetContext(NUL, argc, argv, optionsTable, 0);
poptSetOtherOptionHelp(optCon, "[OPTIONS]* ");
if (argc < 2) {
poptPrintUsage(optCon, stderr, 0);
exit(1);
}
/* Now do options processing, get portname */
while ((c = poptGetNextOpt(optCon)) >= 0) {
switch (c) {
case 'c':
buf[i] = 'c';
break;
SunOS 5.11 Last change: 31 May 2004 17
C Library Functions libpopt(3)
case 'h':
buf[i] = 'h';
break;
case 's':
buf[i] = 's';
break;
case 'n':
buf[i] = 'n';
break;
}
}
portname = poptGetArg(optCon);
if((portname == NUL) !(poptPeekArg(optCon) == NUL))
usage(optCon, 1, "Specify a single port", ".e.g., /dev/cua0");
if (c < -1) {
/* an error occurred during option processing */
fprintf(stderr, "%s: %s0,
poptBadOption(optCon, POPTBADOPTIONOALIAS),
poptStrerror(c));
return 1;
}
/* Print out options, portname chosen */
printf("Options chosen: ");
for(j = 0; j < i ; j])
printf("-%c ", buf[j]);
if(raw) printf("-r ");
if(speed) printf("-b %d ", speed);
printf("0ortname chosen: %s0, portname);
poptFreeContext(optCon);
exit(0);
}
RPM, a popular Linux package management application, uses
several popt features. Many RPM command-line arguments are
implemented using popt aliases, which makes RPM an excellent
example of how to take advantage of the popt library. For
more information about RPM, see http:/www.rpm.org. The popt
source code distribution includes test programs that use all
of the features of the popt libraries in various ways. If a
popt feature does not work for you, check the popt test
code.
FILES
The following files are used by this library:
/usr/lib/libpopt.so Command Line Parser API shared
library
SunOS 5.11 Last change: 31 May 2004 18
C Library Functions libpopt(3)
ATRIBUTES
See attributes(5) for descriptions of the following attri-
butes:
ATRIBUTE TYPE ATRIBUTE VALUE
Availability SUNWlibpopt
Interface stability Volatile
SEE ALSO
getopt(3), attributes(5)
NOTES
Updated by Erwann Chenede, Sun Microsystems Inc., 2003.
Written by Erik W. Troan (ewt@redhat.com), Michael K. John-
son, and Robert Lynch.
SunOS 5.11 Last change: 31 May 2004 19
|