-
Notifications
You must be signed in to change notification settings - Fork 14
/
getopt.c
99 lines (87 loc) · 2.28 KB
/
getopt.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
* This file is part of the Advance project.
*
* Copyright (C) 2002 Andrea Mazzoleni
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#if !HAVE_GETOPT
/* This source is extracted from the DJGPP LIBC library */
#define unconst(var, type) ((type)(var))
/* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
#include <string.h>
#include <stdio.h>
int opterr = 1, optind = 1, optopt = 0;
char *optarg = 0;
#define BADCH (int)'?'
#define EMSG ""
int getopt(int nargc, char *const nargv[], const char *ostr)
{
static const char *place = EMSG; /* option letter processing */
char *oli; /* option letter list index */
char *p;
if (!*place) {
if (optind >= nargc || *(place = nargv[optind]) != '-') {
place = EMSG;
return EOF;
}
if (place[1] && *++place == '-') {
++optind;
place = EMSG;
return EOF;
}
}
if ((optopt = (int)*place++) == (int)':'
|| !(oli = strchr(ostr, optopt))) {
/*
* if the user didn't specify '-' as an option,
* assume it means EOF.
*/
if (optopt == (int)'-')
return EOF;
if (!*place)
++optind;
if (opterr) {
if (!(p = strrchr(*nargv, '/')))
p = *nargv;
else
++p;
fprintf(stderr, "%s: illegal option -- %c\n", p, optopt);
}
return BADCH;
}
if (*++oli != ':') { /* don't need argument */
optarg = NULL;
if (!*place)
++optind;
} else { /* need an argument */
if (*place) /* no white space */
optarg = unconst(place, char *);
else if (nargc <= ++optind) { /* no arg */
place = EMSG;
if (!(p = strrchr(*nargv, '/')))
p = *nargv;
else
++p;
if (opterr)
fprintf(stderr, "%s: option requires an argument -- %c\n", p, optopt);
return BADCH;
}else /* white space */
optarg = nargv[optind];
place = EMSG;
++optind;
}
return optopt; /* dump back option letter */
}
#endif