main shrub/shrubtools / shared / sgetopt.c
 1/* Public domain. */
 2
 3/* sgetopt.c, sgetopt.h: (yet another) improved getopt clone, outer layer
 4D. J. Bernstein, djb@pobox.com.
 5Depends on subgetopt.h, buffer.h.
 6No system requirements.
 719991219: Switched to buffer.h.
 819970208: Cleanups.
 9931201: Baseline.
10No known patent problems.
11
12Documentation in sgetopt.3.
13*/
14
15#include "buffer.h"
16#define SGETOPTNOSHORT
17#include "sgetopt.h"
18#define SUBGETOPTNOSHORT
19#include "subgetopt.h"
20
21#define getopt sgetoptmine
22#define optind subgetoptind
23#define opterr sgetopterr
24#define optproblem subgetoptproblem
25#define optprogname sgetoptprogname
26
27int opterr = 1;
28const char *optprogname = 0;
29
30int getopt(int argc,const char *const *argv,const char *opts)
31{
32  int c;
33  const char *s;
34
35  if (!optprogname) {
36    optprogname = *argv;
37    if (!optprogname) optprogname = "";
38    for (s = optprogname;*s;++s) if (*s == '/') optprogname = s + 1;
39  }
40  c = subgetopt(argc,argv,opts);
41  if (opterr)
42    if (c == '?') {
43      char chp[2]; chp[0] = optproblem; chp[1] = '\n';
44      buffer_puts(buffer_2,optprogname);
45      if (argv[optind] && (optind < argc))
46        buffer_puts(buffer_2,": illegal option -- ");
47      else
48        buffer_puts(buffer_2,": option requires an argument -- ");
49      buffer_put(buffer_2,chp,2);
50      buffer_flush(buffer_2);
51    }
52  return c;
53}