home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 5 Edit / 05-Edit.zip / me34src.zip / me3 / util / argh.c next >
C/C++ Source or Header  |  1995-01-14  |  2KB  |  64 lines

  1. /*
  2.  * ARGH(): simular to GETOPT(3)
  3.  * C Durland 7/85    Public Domain
  4.  *
  5.  * argh(argc,argv,options)
  6.  *  options string is CASE SENSITIVE.  If option letter is followed
  7.  *    by a ':' it means option requires a word.
  8.  *  returns: -1 (error), 0 (done), 1 (OK), 2 (no '-' but a word)
  9.  *  argc, argv & options are unmodified by argh().
  10.  * Notes: It is expected that you will only process the command line
  11.  *    with this program ONCE! (unless you reset optind & optoff).
  12.  *    if 1: &':'||2 (optarg!='\0')
  13.  *    if -1: (optarg==?)
  14.  */
  15.  
  16. #include <stdio.h>
  17. #include <ctype.h>
  18. #include "const.h"
  19.  
  20.     /* the next 3 vars are to be used by the calling pgm */
  21. char *optarg,        /* pointer to word */
  22.      optltr;        /* option letter */
  23. int opterr = TRUE;    /* tell errors?    */
  24.  
  25.     /* Next 2 vars can be used to restart argh() for example if you have
  26.      *   a recursive main()
  27.      */
  28. int optind = 1,        /* index into argv */
  29.     optoff = 0;        /* offset into argv[optind] */
  30.  
  31. argh(argc,argv,options) int argc; char **argv, *options;
  32. {
  33.   char *option, *strchr();
  34.  
  35. loop:
  36.   if (optind>=argc) return 0;    /* no more args in arglist */
  37.   optarg = argv[optind];
  38.   if (optoff==0) /* new arg => check to see if an option */
  39.     if (optarg[0]=='-') optoff++;        /* skip to next char */
  40.     else { optind++; optltr = '?'; return 2; }    /* not option arg */
  41.   if ((optltr = optarg[optoff++]) =='\0')    /* try next arg */
  42.     { optind++; optoff = 0; goto loop; }
  43. /*  optltr = toupper(optltr); */
  44.   if ((option = strchr(options,optltr)) ==(char *)NULL)
  45.   {
  46.     if (opterr) fprintf(stderr,"unknown option: '%c'\n",optltr);
  47.     return -1;        /* not valid option */
  48.   }
  49.   if (option[1]==':')
  50.   {        /* word expected, check next char & skip to next arg */
  51.     optarg = argv[optind++] +optoff; optoff = 0;
  52.     if ( (*optarg)=='\0' )
  53.             /* end of arg so check for word in next arg */
  54.       if (optind>=argc)
  55.       {    /* no more arguments */
  56.         if (opterr)
  57.       fprintf(stderr,"'%c' option requires an argument\n",optltr);
  58.         return -1;
  59.       }
  60.       else optarg = argv[optind++];
  61.   }
  62.   return 1;
  63. }
  64.