]> git.sur5r.net Git - openldap/blob - libraries/liblutil/getopt.c
112616fdceb4b717850c422831cf7eb5eb7190fc
[openldap] / libraries / liblutil / getopt.c
1 /*
2         getopt.c
3
4         modified public-domain AT&T getopt(3)
5         modified by Kurt Zeilenga for inclusion into OpenLDAP
6 */
7
8 #include "portable.h"
9
10 #ifndef HAVE_GETOPT
11
12 #include <stdio.h>
13
14 #include <ac/string.h>
15 #include <ac/unistd.h>
16
17 int opterr = 1;
18 int optind = 1;
19 int optopt;
20 char * optarg;
21
22 static void ERR (char ** argv, char * s, char c)
23 {
24         char errbuf[2];
25
26 #ifdef DF_TRACE_DEBUG
27 printf("DF_TRACE_DEBUG:         static void ERR () in getopt.c\n");
28 #endif
29         if (opterr)
30         {
31                 errbuf[0] = c;
32                 errbuf[1] = '\n';
33                 (void) write(STDERR_FILENO,argv[0],strlen(argv[0]));
34                 (void) write(STDERR_FILENO,s,strlen(s));
35                 (void) write(STDERR_FILENO,errbuf,sizeof errbuf);
36         }
37 }
38
39 int getopt (int argc, char ** argv, char * opts)
40 {
41         static int sp = 1, error = (int) '?';
42         static char sw = '-', eos = '\0', arg = ':';
43         register char c, * cp;
44
45 #ifdef DF_TRACE_DEBUG
46 printf("DF_TRACE_DEBUG:         int getopt () in getopt.c\n");
47 #endif
48         if (sp == 1)
49                 if (optind >= argc || argv[optind][0] != sw
50                 || argv[optind][1] == eos)
51                         return EOF;
52                 else if (strcmp(argv[optind],"--") == 0)
53                 {
54                         optind++;
55                         return EOF;
56                 }
57         c = argv[optind][sp];
58         optopt = (int) c;
59         if (c == arg || (cp = strchr(opts,c)) == NULL)
60         {
61                 ERR(argv,": illegal option--",c);
62                 if (argv[optind][++sp] == eos)
63                 {
64                         optind++;
65                         sp = 1;
66                 }
67                 return error;
68         }
69         else if (*++cp == arg)
70         {
71                 if (argv[optind][sp + 1] != eos)
72                         optarg = &argv[optind++][sp + 1];
73                 else if (++optind >= argc)
74                 {
75                         ERR(argv,": option requires an argument--",c);
76                         sp = 1;
77                         return error;
78                 }
79                 else
80                         optarg = argv[optind++];
81                 sp = 1;
82         }
83         else
84         {
85                 if (argv[optind][++sp] == eos)
86                 {
87                         sp = 1;
88                         optind++;
89                 }
90                 optarg = NULL;
91         }
92         return (int) c;
93 }
94 #endif /* HAVE_GETOPT */