1 #include        <stdio.h>
2 #include <string.h>
3 #define EPR                 fprintf(stderr,
4 #define ERR(str, chr)       if(opterr){EPR "%s%c\n", str, chr);}
5 int     opterr = 1;
6 int     optind = 1;
7 int     optopt;
8 char    *optarg;
9 char    *strchr();
10 
11 int
Getopt(int argc,char * const argv[],const char * opts)12 Getopt (int argc, char *const argv[], const char *opts)
13 {
14         static int sp = 1;
15         register c;
16         register char *cp;
17 
18 	while(optind < argc && argv[optind][0] != '-')
19 		optind++;
20 	if(optind >= argc )
21 		return -1;
22         if (sp == 1)
23                 if (argv[optind][0] != '-' || argv[optind][1] == '\0')
24                         return -1;
25                 else if (strcmp(argv[optind], "--") == 0) {
26                         optind++;
27                         return -1;
28                 }
29         optopt = c = argv[optind][sp];
30         if (c == ':' || (cp=strchr(opts, c)) == 0) {
31                 ERR (": illegal option -- ", c);
32                 if (argv[optind][++sp] == '\0') {
33                         optind++;
34                         sp = 1;
35                 }
36                 return '?';
37         }
38         if (*++cp == ':') {
39                 if (argv[optind][sp+1] != '\0')
40                         optarg = &argv[optind++][sp+1];
41                 else if (++optind >= argc) {
42                         ERR (": option requires an argument -- ", c);
43                         sp = 1;
44                         return '?';
45                 } else
46                         optarg = argv[optind++];
47                 sp = 1;
48         } else {
49                 if (argv[optind][++sp] == '\0') {
50                         sp = 1;
51                         optind++;
52                 }
53                 optarg = 0;
54         }
55         return c;
56 }
57 
58 
59