1 /* 2 * Copyright (c) 1987 Regents of the University of California. 3 * All rights reserved. 4 * 5 * %sccs.include.redist.c% 6 */ 7 8 #if defined(LIBC_SCCS) && !defined(lint) 9 static char sccsid[] = "@(#)getopt.c 4.12 (Berkeley) 06/01/90"; 10 #endif /* LIBC_SCCS and not lint */ 11 12 #include <stdio.h> 13 14 /* 15 * get option letter from argument vector 16 */ 17 int opterr = 1, /* if error message should be printed */ 18 optind = 1, /* index into parent argv vector */ 19 optopt; /* character checked for validity */ 20 char *optarg; /* argument associated with option */ 21 22 #define BADCH (int)'?' 23 #define EMSG "" 24 25 getopt(nargc, nargv, ostr) 26 int nargc; 27 char **nargv, *ostr; 28 { 29 static char *place = EMSG; /* option letter processing */ 30 register char *oli; /* option letter list index */ 31 char *p, *index(), *rindex(); 32 33 if (!*place) { /* update scanning pointer */ 34 if (optind >= nargc || *(place = nargv[optind]) != '-') { 35 place = EMSG; 36 return(EOF); 37 } 38 if (place[1] && *++place == '-') { /* found "--" */ 39 ++optind; 40 place = EMSG; 41 return(EOF); 42 } 43 } /* option letter okay? */ 44 if ((optopt = (int)*place++) == (int)':' || 45 !(oli = index(ostr, optopt))) { 46 /* 47 * if the user didn't specify '-' as an option, 48 * assume it means EOF. 49 */ 50 if (optopt == (int)'-') 51 return(EOF); 52 if (!*place) 53 ++optind; 54 if (opterr) { 55 if (!(p = rindex(*nargv, '/'))) 56 p = *nargv; 57 else 58 ++p; 59 (void)fprintf(stderr, "%s: illegal option -- %c\n", 60 p, optopt); 61 } 62 return(BADCH); 63 } 64 if (*++oli != ':') { /* don't need argument */ 65 optarg = NULL; 66 if (!*place) 67 ++optind; 68 } 69 else { /* need an argument */ 70 if (*place) /* no white space */ 71 optarg = place; 72 else if (nargc <= ++optind) { /* no arg */ 73 place = EMSG; 74 if (!(p = rindex(*nargv, '/'))) 75 p = *nargv; 76 else 77 ++p; 78 if (opterr) 79 (void)fprintf(stderr, 80 "%s: option requires an argument -- %c\n", 81 p, optopt); 82 return(BADCH); 83 } 84 else /* white space */ 85 optarg = nargv[optind]; 86 place = EMSG; 87 ++optind; 88 } 89 return(optopt); /* dump back option letter */ 90 } 91