3.1.3. Source Code for getargs.c

The following code is the C code that defines the functions cfxUsage and getargs, both of which are called by the example listing above. You do not need to include this code with your custom export program (it is automatically linked in if you use the compiler as described in the next section).

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "getargs.h"
/*---------- usage --------------------------------------------------
 * display usage message and exit
 *-------------------------------------------------------------------*/
void cfxUsage (
#ifdef PROTOTYPE
   char **usgmsg, char *errmsg)
#else
   usgmsg, errmsg)
char **usgmsg, *errmsg;
#endif
{
   int n;
   if (NULL != errmsg)
      fprintf (stderr, "ERROR: %s\n", errmsg);
   for (n = 0; NULL != usgmsg[n]; n++)
      fprintf (stderr, "%s\n", usgmsg[n]);
   exit (NULL != errmsg);
}
/*---------- getargs ---------------------------------------------------
 * get option letter from argument vector or terminates on error
 * this is similar to getopt()
 *----------------------------------------------------------------------*/
int argind = 0;  /* index into argv array */
char *argarg;    /* pointer to argument string */
int getargs (
#ifdef PROTOTYPE
   int argc, char **argv, char *ostr)
#else
   argc, argv, ostr)
int argc;
char **argv, *ostr;
#endif
{
   int argopt;
   char *oli;
   static char *place;
   static int nextarg;
   /* initialisation */
   if (!argind)
      nextarg = 1;
   if (nextarg) {  /* update scanning pointer */
      nextarg = 0;
      /* end of arguments */
      if (++argind >= argc || ‘-’ != argv[argind][0])
         return (0);
      place = argarg = &argv[argind][1];
   }
   /* check for valid option */
   if ((argopt = *place++) == ‘:’ ||
      (oli = strchr (ostr, argopt)) == NULL) {
      fprintf (stderr, "invalid command line option `%c’\n", argopt);
      exit (1);
   }
   /* check for an argument */
   if (*++oli != ‘:’) {        /* don’t need argument */
      argarg = NULL;
      if (!*place)
         nextarg = 1;
   }
   else {                      /* need an argument */
      if (!*place) {
         if (++argind >= argc) {
            fprintf (stderr, "missing argument for option `%c’\n", argopt);
            exit (1);
         }
         place = argv[argind];
      }
      argarg = place;
      nextarg = 1;
   }
   return (argopt);    /* return option letter */
}