-
Notifications
You must be signed in to change notification settings - Fork 4
/
getopt.h
61 lines (50 loc) · 1.14 KB
/
getopt.h
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
/*
* This is a version of the public domain getopt implementation by
* Henry Spencer originally posted to net.sources.
*
* This file is in the public domain.
*/
#include <stdio.h>
#include <string.h>
char *optarg; /* Global argument pointer. */
int optind = 0; /* Global argv index. */
int
getopt(int argc, char *argv[], char *optstring)
{
static char *scan = NULL; /* Private scan pointer. */
char c;
char *place;
optarg = NULL;
if (scan == NULL || *scan == '\0') {
if (optind == 0)
optind++;
if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0')
return EOF;
if (argv[optind][1] == '-' && argv[optind][2] == '\0') {
optind++;
return EOF;
}
scan = argv[optind]+1;
optind++;
}
c = *scan++;
place = strchr(optstring, c);
if (place == NULL || c == ':') {
fprintf(stderr, "%s: unknown option -%c\n", argv[0], c);
return '?';
}
place++;
if (*place == ':') {
if (*scan != '\0') {
optarg = scan;
scan = NULL;
} else if( optind < argc ) {
optarg = argv[optind];
optind++;
} else {
fprintf(stderr, "%s: option requires argument -%c\n", argv[0], c);
return ':';
}
}
return c;
}