121397Smckusick /* 221397Smckusick * Copyright (c) 1985 Regents of the University of California. 321397Smckusick * All rights reserved. The Berkeley software License Agreement 421397Smckusick * specifies the terms and conditions for redistribution. 521397Smckusick */ 621397Smckusick 726524Sdonn #if defined(LIBC_SCCS) && !defined(lint) 8*32111Sbostic static char sccsid[] = "@(#)getopt.c 4.4 (Berkeley) 09/04/87"; 926524Sdonn #endif LIBC_SCCS and not lint 1021397Smckusick 1121397Smckusick #include <stdio.h> 1221397Smckusick 1321397Smckusick /* 1421397Smckusick * get option letter from argument vector 1521397Smckusick */ 1625264Smckusick int opterr = 1, /* if error message should be printed */ 1721397Smckusick optind = 1, /* index into parent argv vector */ 1821397Smckusick optopt; /* character checked for validity */ 1921397Smckusick char *optarg; /* argument associated with option */ 2021397Smckusick 2121397Smckusick #define BADCH (int)'?' 2221397Smckusick #define EMSG "" 23*32111Sbostic #define tell(s) { \ 24*32111Sbostic if (opterr) { \ 25*32111Sbostic fputs(*nargv, stderr); \ 26*32111Sbostic fputs(s, stderr); \ 27*32111Sbostic fputc(optopt, stderr); \ 28*32111Sbostic fputc((int)'\n', stderr); \ 29*32111Sbostic } \ 30*32111Sbostic return(BADCH); \ 31*32111Sbostic } 3221397Smckusick 33*32111Sbostic getopt(nargc, nargv, ostr) 34*32111Sbostic int nargc; 35*32111Sbostic char **nargv, *ostr; 3621397Smckusick { 37*32111Sbostic static char *place = EMSG; /* option letter processing */ 38*32111Sbostic register char *oli; /* option letter list index */ 3921397Smckusick char *index(); 4021397Smckusick 41*32111Sbostic if (!*place) { /* update scanning pointer */ 42*32111Sbostic if (optind >= nargc || *(place = nargv[optind]) != '-' || 43*32111Sbostic !*++place) 44*32111Sbostic return(EOF); 45*32111Sbostic if (*place == '-') { /* found "--" */ 4621397Smckusick ++optind; 4721397Smckusick return(EOF); 4821397Smckusick } 49*32111Sbostic } /* option letter okay? */ 50*32111Sbostic if ((optopt = (int)*place++) == (int)':' || 51*32111Sbostic !(oli = index(ostr, optopt))) { 52*32111Sbostic if (!*place) 53*32111Sbostic ++optind; 5421397Smckusick tell(": illegal option -- "); 5521397Smckusick } 56*32111Sbostic if (*++oli != ':') { /* don't need argument */ 5721397Smckusick optarg = NULL; 58*32111Sbostic if (!*place) 59*32111Sbostic ++optind; 6021397Smckusick } 61*32111Sbostic else { /* need an argument */ 62*32111Sbostic if (*place) /* no white space */ 63*32111Sbostic optarg = place; 6421397Smckusick else if (nargc <= ++optind) { /* no arg */ 6521397Smckusick place = EMSG; 6621397Smckusick tell(": option requires an argument -- "); 6721397Smckusick } 68*32111Sbostic else /* white space */ 69*32111Sbostic optarg = nargv[optind]; 7021397Smckusick place = EMSG; 7121397Smckusick ++optind; 7221397Smckusick } 73*32111Sbostic return(optopt); /* dump back option letter */ 7421397Smckusick } 75