1/* 2 * This file was copied from the following newsgroup posting: 3 * 4 * Newsgroups: mod.std.unix 5 * Subject: public domain AT&T getopt source 6 * Date: 3 Nov 85 19:34:15 GMT 7 * 8 * Here's something you've all been waiting for: the AT&T public domain 9 * source for getopt(3). It is the code which was given out at the 1985 10 * UNIFORUM conference in Dallas. I obtained it by electronic mail 11 * directly from AT&T. The people there assure me that it is indeed 12 * in the public domain. 13 */ 14 15#include <stdio.h> 16#include <string.h> 17 18static int optind = 1; 19static int optopt; 20static char *optarg; 21 22static int 23getopt(int argc, char *argv[], const char *opts) { 24 static int sp = 1; 25 int c; 26 char *cp; 27 28 if (sp == 1) { 29 if (optind >= argc || 30 argv[optind][0] != '-' || argv[optind][1] == '\0') 31 return EOF; 32 else if (!strcmp(argv[optind], "--")) { 33 optind++; 34 return EOF; 35 } 36 } 37 optopt = c = argv[optind][sp]; 38 if (c == ':' || !(cp = strchr(opts, c))) { 39 fprintf(stderr, ": illegal option -- %c\n", c); 40 if (argv[optind][++sp] == '\0') { 41 optind++; 42 sp = 1; 43 } 44 return '?'; 45 } 46 if (*++cp == ':') { 47 if (argv[optind][sp+1] != '\0') 48 optarg = &argv[optind++][sp+1]; 49 else if (++optind >= argc) { 50 fprintf(stderr, ": option requires an argument -- %c\n", c); 51 sp = 1; 52 return '?'; 53 } else 54 optarg = argv[optind++]; 55 sp = 1; 56 } else { 57 if (argv[optind][++sp] == '\0') { 58 sp = 1; 59 optind++; 60 } 61 optarg = NULL; 62 } 63 64 return c; 65} 66