lcc.glewis@seas.ucla.edu (07/11/89)
Greetings! I have seen many comments concerning the availability of a UNIX-style getopt() function recently. I wrote my own a bit over a year ago which I am posting for general use. It was originally written for DOS and OS/2, but I have also used it in other more diverse environments [MetaWare HighC-386? ;)]. I haven't had time to port it to Minix yet, but here it is. Porting it should be trivial. -------Cut here------------------------------------------------------------- /* * GETOPT.C * * This subroutine provides the functionality of the UNIX (TM) System * getopt(3c) library routine for MS/PC-DOS and OS/2. Porting getopt() to * Minix should be trivial. Functionality has been extended by the * addition of 'getoptinit()', a function that can be called to * reinitialize for another pass through the options list. * * Author: Gerald L. Lewis * Date: February 18, 1988 * * I make this version of getopt() freely available to the public domain * with no warranty whatsoever. The only requirement is that the authorship * note and version date remain intact. * */ #include <stdio.h> #include <string.h> char *optarg = NULL; /* Points to start of argument when : found */ int optind = 1; /* Options index (skips over name operand) */ int opterr = 0; /* Used to override default error message */ static int off = 1; /* Internal option list offset */ void getoptinit(void) /* Resets getopt global variables */ { optarg = NULL; optind = 1; opterr = 0; off = 1; } int getopt(int argc, char *argv[], char *optstring) { char *cp; int ch; optarg = NULL; while ( optind < argc ) { if ( argv[optind][0] != '-' ) /* Only interested in options */ { off = 1; return(EOF); } if ( argv[optind][1] == '-' ) /* "--" escapes getopt */ { ++optind; off = 1; return(EOF); } if ( (ch = argv[optind][off++]) == '\0' ) { optind++; off = 1; continue; } if ( (cp = strchr(optstring, ch)) == NULL) { if ( !opterr ) fprintf(stderr, "Unknown option -%c\n", ch); return('?'); } else if ( *(cp + 1) != ':' ) return(ch); if ( argv[optind][off] != '\0' ) { optarg = &argv[optind++][off]; off = 1; return(ch); } ++optind; if ( (optind >= argc) || (argv[optind][0] == '-' ) ) { if ( !opterr ) fprintf(stderr, "Missing argument for option -%c\n", ch); return('?'); } optarg = argv[optind++]; off = 1; return(ch); } return(EOF); } -------Cut here------------------------------------------------------------- Gary Lewis lcc.glewis@seas.ucla.edu