]> git.sur5r.net Git - cc65/blob - libsrc/common/getopt.c
Merge pull request #659 from polluks/patch-10
[cc65] / libsrc / common / getopt.c
1 /*
2 ** This is part of a changed public domain getopt implementation that
3 ** had the following text on top:
4 **
5 **      I got this off net.sources from Henry Spencer.
6 **      It is a public domain getopt(3) like in System V.
7 **      I have made the following modifications:
8 **
9 **      A test main program was added, ifdeffed by GETOPT.
10 **      This main program is a public domain implementation
11 **      of the getopt(1) program like in System V.  The getopt
12 **      program can be used to standardize shell option handling.
13 **              e.g.  cc -DGETOPT getopt.c -o getopt
14 */
15
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <unistd.h>
20
21 #define ARGCH    ':'
22 #define BADCH    '?'
23 #define EMSG     ""
24
25 int opterr = 1;                 /* useless, never set or used */
26 int optind = 1;                 /* index into parent argv vector */
27 int optopt;                     /* character checked for validity */
28
29 char *optarg;                   /* argument associated with option */
30
31 #define tell(s) fputs(*argv,stderr);fputs(s,stderr); \
32                 fputc(optopt,stderr);fputc('\n',stderr);return(BADCH);
33
34 int __fastcall__ getopt (int argc, char* const* argv, const char* optstring)
35 /* Get option letter from argument vector */
36 {
37     static char *place = EMSG;  /* option letter processing */
38
39     register char *oli;         /* option letter list index */
40
41     if (!*place) {              /* update scanning pointer */
42         if (optind >= argc || *(place = argv[optind]) != '-' || !*++place) {
43             return (EOF);
44         }
45         if (*place == '-') {
46             /* found "--" */
47             ++optind;
48             return (EOF);
49         }
50     }
51
52     /* option letter okay? */
53     if ((optopt = (int) *place++) == ARGCH ||
54         !(oli = strchr (optstring, optopt))) {
55         if (!*place) {
56             ++optind;
57         }
58         tell (": illegal option -- ");
59     }
60     if (*++oli != ARGCH) {
61         /* don't need argument */
62         optarg = NULL;
63         if (!*place) {
64             ++optind;
65         }
66     } else {
67         /* need an argument */
68         if (*place) {
69             /* no white space */
70             optarg = place;
71         }
72         else if (argc <= ++optind) {   /* no arg */
73             place = EMSG;
74             tell (": option requires an argument -- ");
75         } else {
76             /* white space */
77             optarg = argv[optind];
78         }
79         place = EMSG;
80         ++optind;
81     }
82     return (optopt);            /* dump back option letter */
83 }
84