1 /* 2 * Copyright (c) 1985 Regents of the University of California. 3 * All rights reserved. The Berkeley software License Agreement 4 * specifies the terms and conditions for redistribution. 5 */ 6 7 #if defined(LIBC_SCCS) && !defined(lint) 8 static char sccsid[] = "@(#)getopt.c 4.4 (Berkeley) 09/04/87"; 9 #endif LIBC_SCCS and not lint 10 11 #include <stdio.h> 12 13 /* 14 * get option letter from argument vector 15 */ 16 int opterr = 1, /* if error message should be printed */ 17 optind = 1, /* index into parent argv vector */ 18 optopt; /* character checked for validity */ 19 char *optarg; /* argument associated with option */ 20 21 #define BADCH (int)'?' 22 #define EMSG "" 23 #define tell(s) { \ 24 if (opterr) { \ 25 fputs(*nargv, stderr); \ 26 fputs(s, stderr); \ 27 fputc(optopt, stderr); \ 28 fputc((int)'\n', stderr); \ 29 } \ 30 return(BADCH); \ 31 } 32 33 getopt(nargc, nargv, ostr) 34 int nargc; 35 char **nargv, *ostr; 36 { 37 static char *place = EMSG; /* option letter processing */ 38 register char *oli; /* option letter list index */ 39 char *index(); 40 41 if (!*place) { /* update scanning pointer */ 42 if (optind >= nargc || *(place = nargv[optind]) != '-' || 43 !*++place) 44 return(EOF); 45 if (*place == '-') { /* found "--" */ 46 ++optind; 47 return(EOF); 48 } 49 } /* option letter okay? */ 50 if ((optopt = (int)*place++) == (int)':' || 51 !(oli = index(ostr, optopt))) { 52 if (!*place) 53 ++optind; 54 tell(": illegal option -- "); 55 } 56 if (*++oli != ':') { /* don't need argument */ 57 optarg = NULL; 58 if (!*place) 59 ++optind; 60 } 61 else { /* need an argument */ 62 if (*place) /* no white space */ 63 optarg = place; 64 else if (nargc <= ++optind) { /* no arg */ 65 place = EMSG; 66 tell(": option requires an argument -- "); 67 } 68 else /* white space */ 69 optarg = nargv[optind]; 70 place = EMSG; 71 ++optind; 72 } 73 return(optopt); /* dump back option letter */ 74 } 75