1 /* 2 getopt.c 3 4 */ 5 6 #include <errno.h> 7 #include <string.h> 8 #include <stdio.h> 9 10 int xoptind = 1; /* index of which argument is next */ 11 char *xoptarg; /* pointer to argument of current option */ 12 int xopterr = 0; /* allow error message */ 13 14 static char *letP = NULL; /* remember next option char's location */ 15 char SW = '-'; /* DOS switch character, either '-' or '/' */ 16 17 /* 18 Parse the command line options, System V style. 19 20 Standard option syntax is: 21 22 option ::= SW [optLetter]* [argLetter space* argument] 23 24 */ 25 xgetopt(int argc,char * argv[],char * optionS)26int xgetopt(int argc, char *argv[], char *optionS) 27 { 28 unsigned char ch; 29 char *optP; 30 31 if (SW == 0) { 32 SW = '/'; 33 } 34 35 if (argc > xoptind) { 36 if (letP == NULL) { 37 if ((letP = argv[xoptind]) == NULL || 38 *(letP++) != SW) goto gopEOF; 39 if (*letP == SW) { 40 xoptind++; goto gopEOF; 41 } 42 } 43 if (0 == (ch = *(letP++))) { 44 xoptind++; goto gopEOF; 45 } 46 if (':' == ch || (optP = strchr(optionS, ch)) == NULL) 47 goto gopError; 48 if (':' == *(++optP)) { 49 xoptind++; 50 if (0 == *letP) { 51 if (argc <= xoptind) goto gopError; 52 letP = argv[xoptind++]; 53 } 54 xoptarg = letP; 55 letP = NULL; 56 } else { 57 if (0 == *letP) { 58 xoptind++; 59 letP = NULL; 60 } 61 xoptarg = NULL; 62 } 63 return ch; 64 } 65 gopEOF: 66 xoptarg = letP = NULL; 67 return EOF; 68 69 gopError: 70 xoptarg = NULL; 71 errno = EINVAL; 72 if (xopterr) 73 perror ("get command line option"); 74 return ('?'); 75 } 76