Change all files that I own to use the official DragonFly Project
[dragonfly.git] / contrib / top / getopt.c
1 /*
2  * "getopt" routine customized for top.
3  */
4
5 /*
6  * Many modern-day Unix implementations already have this function
7  * in libc.  The standard "getopt" is perfectly sufficient for top's
8  * needs.  If such a function exists in libc then you certainly don't
9  * need to compile this one in.  To prevent this function from being 
10  * compiled, define "HAVE_GETOPT".  This is usually done in the "CFLAGS"
11  * line of the corresponding machine module.
12  */
13
14 /*
15  * This empty declaration exists solely to placate overexhuberant C
16  * compilers that like to warn you about content-free files.
17  */
18 static void __empty();
19
20 #ifndef HAVE_GETOPT
21
22 /*LINTLIBRARY*/
23
24 #include "os.h"
25 #ifndef NULL
26 #define NULL    0
27 #endif
28 #ifndef EOF
29 #define EOF     (-1)
30 #endif
31 #define ERR(s, c)       if(opterr){\
32         extern int write();\
33         char errbuf[2];\
34         errbuf[0] = c; errbuf[1] = '\n';\
35         (void) write(2, argv[0], strlen(argv[0]));\
36         (void) write(2, s, strlen(s));\
37         (void) write(2, errbuf, 2);}
38
39
40 int     opterr = 1;
41 int     optind = 1;
42 int     optopt;
43 char    *optarg;
44
45 int
46 getopt(argc, argv, opts)
47 int     argc;
48 char    **argv, *opts;
49 {
50         static int sp = 1;
51         register int c;
52         register char *cp;
53
54         if(sp == 1)
55                 if(optind >= argc ||
56                    argv[optind][0] != '-' || argv[optind][1] == '\0')
57                         return(EOF);
58                 else if(strcmp(argv[optind], "--") == 0) {
59                         optind++;
60                         return(EOF);
61                 }
62         optopt = c = argv[optind][sp];
63         if(c == ':' || (cp=strchr(opts, c)) == NULL) {
64                 ERR(": unknown option, -", c);
65                 if(argv[optind][++sp] == '\0') {
66                         optind++;
67                         sp = 1;
68                 }
69                 return('?');
70         }
71         if(*++cp == ':') {
72                 if(argv[optind][sp+1] != '\0')
73                         optarg = &argv[optind++][sp+1];
74                 else if(++optind >= argc) {
75                         ERR(": argument missing for -", c);
76                         sp = 1;
77                         return('?');
78                 } else
79                         optarg = argv[optind++];
80                 sp = 1;
81         } else {
82                 if(argv[optind][++sp] == '\0') {
83                         sp = 1;
84                         optind++;
85                 }
86                 optarg = NULL;
87         }
88         return(c);
89 }
90 #endif /* HAVE_GETOPT */