Lely core libraries  2.2.5
getopt.c
Go to the documentation of this file.
1 
23 #include "libc.h"
24 #include <lely/libc/unistd.h>
25 
26 #if !LELY_HAVE_UNISTD_H
27 
28 #include <assert.h>
29 #include <stddef.h>
30 #include <stdio.h>
31 
32 char *optarg;
33 int optind = 1;
34 int opterr = 1;
35 int optopt;
36 
41 static int optoff;
42 
43 int
44 getopt(int argc, char *const argv[], const char *optstring)
45 {
46  assert(argv);
47  assert(optstring);
48 
49  optarg = NULL;
50 
51  // Check whether any arguments remain.
52  if (optind >= argc || !argv[optind])
53  return -1;
54  // Continue with the next option in the current argument.
55  char *cp = argv[optind] + optoff;
56  // If this is a new argument, check if it is an option argument.
57  if (!optoff) {
58  // An option argument begins with '-'.
59  if (*cp++ != '-' || !*cp)
60  return -1;
61  // A double dash ("--") denotes the end of option arguments.
62  if (*cp == '-' && !cp[1]) {
63  optind++;
64  return -1;
65  }
66  optoff = 1;
67  }
68  int c = *cp++;
69  // Update the index and offset of the next option.
70  if (*cp) {
71  optoff++;
72  } else {
73  optind++;
74  optoff = 0;
75  }
76 
77  // Check if the option character occurs in `optstring`.
78  const char *op = optstring;
79  while (*op && (*op == ':' || *op == '?' || *op != c))
80  op++;
81  if (!*op) {
82  optopt = c;
83  if (opterr && *optstring != ':')
84  fprintf(stderr, "%s: illegal option -- %c\n", argv[0],
85  optopt);
86  return '?';
87  }
88 
89  // If the option does not take an argument, we are done.
90  if (*++op != ':')
91  return c;
92 
93  optind++;
94  optoff = 0;
95  if (*cp) {
96  // If any characters remain in the current argument, they form
97  // the argument for the option...
98  optarg = cp;
99  } else {
100  // ... otherwise, the next argument is used, if it exists.
101  if (optind > argc) {
102  optopt = c;
103  if (opterr && *optstring != ':')
104  fprintf(stderr,
105  "%s: option requires an "
106  "argument -- %c\n",
107  argv[0], optopt);
108  return *optstring == ':' ? ':' : '?';
109  }
110  optarg = argv[optind - 1];
111  }
112  return c;
113 }
114 
115 #endif // !LELY_HAVE_UNISTD_H
libc.h
stdio.h
unistd.h
stddef.h