getopt.c

Go to the documentation of this file.
00001 /*
00002 Newsgroups: mod.std.unix
00003 Subject: public domain AT&T getopt source
00004 Date: 3 Nov 85 19:34:15 GMT
00005 
00006 Here's something you've all been waiting for:  the AT&T public domain
00007 source for getopt(3).  It is the code which was given out at the 1985
00008 UNIFORUM conference in Dallas.  I obtained it by electronic mail
00009 directly from AT&T.  The people there assure me that it is indeed
00010 in the public domain.
00011 */
00012 
00013 
00014 /*LINTLIBRARY*/
00015 #define NULL    0
00016 #define EOF     (-1)
00017 #define ERR(s, c)       if(opterr){\
00018         extern int strlen(), write();\
00019         char errbuf[2];\
00020         errbuf[0] = c; errbuf[1] = '\n';\
00021         (void) write(2, argv[0], (unsigned)strlen(argv[0]));\
00022         (void) write(2, s, (unsigned)strlen(s));\
00023         (void) write(2, errbuf, 2);}
00024 
00025 extern int strcmp();
00026 extern char *strchr();
00027 
00028 int     opterr = 1;
00029 int     optind = 1;
00030 int     optopt;
00031 char    *optarg;
00032 
00033 int
00034 getopt(argc, argv, opts)
00035 int     argc;
00036 char    **argv, *opts;
00037 {
00038         static int sp = 1;
00039         register int c;
00040         register char *cp;
00041 
00042         if(sp == 1)
00043                 if(optind >= argc ||
00044                    argv[optind][0] != '-' || argv[optind][1] == '\0')
00045                         return(EOF);
00046                 else if(strcmp(argv[optind], "--") == NULL) {
00047                         optind++;
00048                         return(EOF);
00049                 }
00050         optopt = c = argv[optind][sp];
00051         if(c == ':' || (cp=strchr(opts, c)) == NULL) {
00052                 ERR(": illegal option -- ", c);
00053                 if(argv[optind][++sp] == '\0') {
00054                         optind++;
00055                         sp = 1;
00056                 }
00057                 return('?');
00058         }
00059         if(*++cp == ':') {
00060                 if(argv[optind][sp+1] != '\0')
00061                         optarg = &argv[optind++][sp+1];
00062                 else if(++optind >= argc) {
00063                         ERR(": option requires an argument -- ", c);
00064                         sp = 1;
00065                         return('?');
00066                 } else
00067                         optarg = argv[optind++];
00068                 sp = 1;
00069         } else {
00070                 if(argv[optind][++sp] == '\0') {
00071                         sp = 1;
00072                         optind++;
00073                 }
00074                 optarg = NULL;
00075         }
00076         return(c);
00077 }

Generated on Fri Apr 14 22:56:46 2006 for minix by  doxygen 1.4.6