Product SiteDocumentation Site

15.2.3. Handling Errors

Inside your while loop processing the command-line arguments, you can call poptBadOption to get the option that was bad, and poptStrerror to look up the error message associated with the error.
For poptBadOption, you need to pass in the context, and a bitmask of flags. Normally, pass 0 for no flags or POPT_BADOPTION_NOALIAS, which tells popt to return the actual option, not a value defined in an alias. This makes poptBadOption return the option closest to, if not exactly the same as, what the user entered, which makes for better error reporting.
The poptBadOption function signature follows:
char * poptBadOption(poptContext context, int flags);
Pass the error number returned by poptGetOptArg to poptStrerror to get the standard error message for that option:
const char * poptStrerror(const int error_code);
You can combine these and print out an error with code like the following:
fprintf( stderr, "Error with option [%s]\n %s",
poptBadOption(context, POPT_BADOPTION_NOALIAS),
poptStrerror(error_code);
To print out a usage message, call poptPrintUsage:
void poptPrintUsage(poptContext context,
FILE *output,
int flags);
This function prints out the usage help information, which is a useful function when the user has called a program with incomplete or wrong options.