source: trunk/sys/dietlibc/getopt.c @ 370

Last change on this file since 370 was 1, checked in by alain, 7 years ago

First import

File size: 1.5 KB
Line 
1#include <string.h>
2#include <getopt.h>
3
4static void getopterror(int which) {
5  static char error1[]="Unknown option `-x'.\n";
6  static char error2[]="Missing argument for `-x'.\n";
7  if (opterr) {
8    if (which) {
9      error2[23]=optopt;
10      write(2,error2,28);
11    } else {
12      error1[17]=optopt;
13      write(2,error1,22);
14    }
15  }
16}
17
18int getopt(int argc, char * const argv[], const char *optstring) {
19  static int lastidx,lastofs;
20  char *tmp;
21  if (optind==0) { optind=1; lastidx=0; }       /* whoever started setting optind to 0 should be shot */
22again:
23  if (optind>argc || !argv[optind] || *argv[optind]!='-' || argv[optind][1]==0)
24    return -1;
25  if (argv[optind][1]=='-' && argv[optind][2]==0) {
26    ++optind;
27    return -1;
28  }
29  if (lastidx!=optind) {
30    lastidx=optind; lastofs=0;
31  }
32  optopt=argv[optind][lastofs+1];
33  if ((tmp=strchr(optstring,optopt))) {
34    if (*tmp==0) {      /* apparently, we looked for \0, i.e. end of argument */
35      ++optind;
36      goto again;
37    }
38    if (tmp[1]==':') {  /* argument expected */
39      if (tmp[2]==':' || argv[optind][lastofs+2]) {     /* "-foo", return "oo" as optarg */
40        if (!*(optarg=argv[optind]+lastofs+2)) optarg=0;
41        goto found;
42      }
43      optarg=argv[optind+1];
44      if (!optarg) {    /* missing argument */
45        ++optind;
46        if (*optstring==':') return ':';
47        getopterror(1);
48        return ':';
49      }
50      ++optind;
51    } else {
52      ++lastofs;
53      return optopt;
54    }
55found:
56    ++optind;
57    return optopt;
58  } else {      /* not found */
59    getopterror(0);
60    ++optind;
61    return '?';
62  }
63}
Note: See TracBrowser for help on using the repository browser.