home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 11 Util / 11-Util.zip / CVTICONS.ZIP / GETOPT.C < prev    next >
Text File  |  1991-06-29  |  2KB  |  82 lines

  1. /*********************************** Function GetOpt ************************/
  2. /* takes an argument count and an array of pointers to argument strings     */
  3. /* and a string variable that is a list of allowable option flags.          */
  4. /* Single letters, case sensitive, and single digits are acceptable.        */
  5. /* if a valid option is followed by a colon, GetOpt will return an argument */
  6. /* that follows that option.  gnOptErr if set to 0 will turn of the error   */
  7. /* message display, gnOptInd is the index to the current option being       */
  8. /* processed.  gszOptArg is where the parameter following an option will be */
  9. /* returned in.                                    */
  10. /****************************************************************************/
  11. #define NULL 0
  12. #define EOF (-1)
  13.  
  14. #include <string.h>
  15. #include <stdio.h>
  16.  
  17. #define ERR(sz, nC)   if(gnOptErr){\
  18.         char szErrBuf[2];\
  19.         szErrBuf[0] = nC; szErrBuf[1] ='\0';\
  20.         (void) printf("%s : ",szArgv[0]);\
  21.         (void) printf(sz);\
  22.         (void) printf(" : %s\n",szErrBuf);}
  23.  
  24. int  gnOptErr = 1;
  25. int  gnOptInd = 1;
  26. int  gnOptOpt;
  27. char *gszOptArg;
  28.  
  29. int GetOpt(int nArgc, char **szArgv, char *szOpts)
  30. {
  31.   static   int  nSp = 1;
  32.   register int  nC;
  33.   register char *szP;
  34.  
  35.   if (nSp == 1)
  36.     if(gnOptInd >= nArgc || szArgv[gnOptInd][0] != '-' ||
  37.                 szArgv[gnOptInd][1] == '\0')
  38.       return EOF;
  39.   else
  40.     if (strcmp(szArgv[gnOptInd], "--") == NULL)
  41.     {
  42.       gnOptInd++;
  43.       return EOF;
  44.     }
  45.   gnOptOpt = nC = szArgv[gnOptInd][nSp];
  46.   if(nC == ':' || (szP = strchr(szOpts, nC)) == NULL)
  47.   {
  48.     ERR("Illegal option --", (char) nC);
  49.     if(szArgv[gnOptInd][++nSp] == '\0')
  50.     {
  51.       gnOptInd++;
  52.       nSp = 1;
  53.     }
  54.     return '?';
  55.   }
  56.   if(*++szP == ':')
  57.   {
  58.     if(szArgv[gnOptInd][nSp+1] != '\0')
  59.       gszOptArg = &szArgv[gnOptInd++][nSp+1];
  60.     else
  61.       if(++gnOptInd >= nArgc)
  62.       {
  63.     ERR("Option requires an argument -- ", (char)nC);
  64.     nSp = 1;
  65.     return '?';
  66.       }
  67.       else
  68.     gszOptArg = szArgv[gnOptInd++];
  69.     nSp = 1;
  70.   }
  71.   else
  72.   {
  73.     if(szArgv[gnOptInd][++nSp] == '\0')
  74.     {
  75.       nSp = 1;
  76.       gnOptInd++;
  77.     }
  78.     gszOptArg = NULL;
  79.   }
  80.   return(nC);
  81. }
  82.