-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgetopt.c
97 lines (92 loc) · 2.06 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
#include <string.h>
#include <unistd.h>
// Часть контекста процесса
extern /* const */char *optarg;
extern int opterr, optind, optopt;
int getopt(int argc, char * const argv[], const char *optstring)
{
const char * s = argv[optind];
if (s==NULL) return -1;
if (s[0]!='-') return -1;
optopt = s[0];
if (optopt=='\0') return -1;
if (s[2]=='\0'){
optind++;
if (optopt=='-') return -1;
s = argv[optind];
if (s==NULL || optind >= argc) return ':';
} else
s+= 2;
const char* p = strchr(optstring, optopt);
if (p==NULL) return '?';// unrecognized option
if (p[1]==':') {
optind++;
optarg = (char *)s;
}
return p[0];
}
#ifdef TEST_GETOPT
/* Tests
This code accepts any of the following as equivalent:
cmd −ao arg path path
cmd −a −o arg path path
cmd −o arg −a path path
cmd −a −o arg − − path path
cmd −a −oarg path path
cmd −aoarg path path
*/
/*! Parsing Command Line Options
The following code fragment shows how you might process the arguments for a utility that can
take the mutually-exclusive options a and b and the options f and o, both of which require
arguments: */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int c;
int bflg = 0, aflg = 0, errflg = 0;
char *ifile;
char *ofile;
// . . .
while ((c = getopt(argc, argv, ":abf:o:")) != -1) {
switch(c) {
case 'a':
if (bflg)
errflg++;
else
aflg++;
break;
case 'b':
if (aflg)
errflg++;
else
bflg++;
break;
case 'f':
ifile = optarg;
break;
case 'o':
ofile = optarg;
break;
case ':': /* -f or -o without operand */
fprintf(stderr, "Option -%c requires an operand\n", optopt);
errflg++;
break;
case '?':
fprintf(stderr, "Unrecognized option: '-%c'\n", optopt);
errflg++;
break;
}
}
if (errflg) {
fprintf(stderr, "usage: . . . \n");
exit(2);
}
for ( ; optind < argc; optind++) {
if (access(argv[optind], R_OK)) {
// . . .
}
}
}
#endif