-
Notifications
You must be signed in to change notification settings - Fork 1
/
getopt_tabified.c
96 lines (79 loc) · 2.13 KB
/
getopt_tabified.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
#include "inc/getopt.h"
/* This function gets the next option letter from the console input.
It is supposed to be equivalent to the UNIX getopt function.
Options are preceeded by a dash, currently a slash is not allowed.
Multiple options after one dash are valid, and arguments after
the option with a colon between are supported.*/
/* Common varibles. */
int opterr = 1, /* error messages printed? default: yes */
optind = 1, /* index into parent argv vector */
optopt; /* character checked for validity */
char *optarg; /* argument associated with option */
#define EMSG ""
char *progname; /* may also be defined elsewhere */
static void
error(char *pch) /* error message routine */
{
if (!opterr)
return; /* without printing */
fprintf(stderr, "%s: %s: %c\n",
((NULL != progname) ? progname : "getopt"), pch, optopt);
}
int
getopt(int argc, char *argv[], char *ostr)
{
static char *place = EMSG; /* option letter processing */
char *oli; /* option letter list index */
progname = argv[0];
if (!*place)
{ /* update scanning pointer */
if (optind >= argc ||
(*(place = argv[optind]) != '-' &&
*(place = argv[optind]) != '/') ||
!*++place)
{
return EOF;
}
if (*place == '-')
{ /* found "--"; ignore; (end of options) */
++optind;
return EOF;
}
}
/* option letter okay? */
optopt = (int)*place;
++place;
oli = strchr(ostr, optopt);
if ((optopt == (int)':') ||
!(oli = strchr(ostr, optopt)))
{
if (!*place)
++optind;
error("illegal option");
return BADCH;
}
if (*++oli != ':') /* Check for argument after option */
{ /* don't need argument */
optarg = NULL;
if (!*place)
++optind;
}
else
{ /* need an argument */
if (*place)
optarg = place; /* no white space */
else
if (argc <= ++optind)
{ /* no arg */
place = EMSG;
error("option requires an argument");
return BADCH;
}
else
optarg = argv[optind]; /* white space */
place = EMSG;
++optind;
}
return optopt; /* return option letter */
}
/* vi: set sw=4 ts=4 sts=4 noet :iv */