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