comparison getopt.c @ 0:c55ea9478c80

Hello Gensokyo!
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Tue, 21 May 2013 10:29:21 +0200
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:c55ea9478c80
1 /*
2 * getopt - get option letter from argv
3 *
4 * This is a version of the public domain getopt() implementation by
5 * Henry Spencer, changed for 4.3BSD compatibility (in addition to System V).
6 * It allows rescanning of an option list by setting optind to 0 before
7 * calling, which is why we use it even if the system has its own (in fact,
8 * this one has a unique name so as not to conflict with the system's).
9 * Thanks to Dennis Ferguson for the appropriate modifications.
10 *
11 * This file is in the Public Domain.
12 */
13
14 #include <string.h>
15 #include <unistd.h>
16
17 char *optarg; /* Global argument pointer. */
18 int optind = 0; /* Global argv index. */
19 int opterr = 1; /* for compatibility, should error be printed? */
20 int optopt; /* for compatibility, option character checked */
21
22 static char *scan = NULL; /* Private scan pointer. */
23
24 /*
25 * Print message about a bad option.
26 */
27 static int badopt(const char *msg, int ch)
28 {
29 if (opterr) {
30 write(2, msg, strlen(msg));
31 write(2, &ch, 1);
32 write(2, "\n", 1);
33 }
34 return ('?');
35 }
36
37 int getopt(int argc, char *const argv[], const char *optstring)
38 {
39 register char c;
40 register const char *place;
41 optarg = NULL;
42
43 if (optind == 0) {
44 scan = NULL;
45 optind++;
46 }
47
48 if (scan == NULL || *scan == '\0') {
49 if (optind >= argc
50 || argv[optind][0] != '-'
51 || argv[optind][1] == '\0') {
52 return (-1);
53 }
54 if (argv[optind][1] == '-'
55 && argv[optind][2] == '\0') {
56 optind++;
57 return (-1);
58 }
59 scan = argv[optind++]+1;
60 }
61
62 c = *scan++;
63 optopt = c & 0377;
64 for (place = optstring; place != NULL && *place != '\0'; ++place)
65 if (*place == c)
66 break;
67
68 if (place == NULL || *place == '\0' || c == ':' || c == '?') {
69 return (badopt("getopt: unknown option -", c));
70 }
71
72 place++;
73 if (*place == ':') {
74 if (*scan != '\0') {
75 optarg = scan;
76 scan = NULL;
77 } else if (optind >= argc) {
78 return (badopt("getopt: option requires argument -", c));
79 } else {
80 optarg = argv[optind++];
81 }
82 }
83 return (c & 0377);
84 }
85