]> cloudbase.mooo.com Git - z180-stamp.git/blob - avr/getopt-min.c
Merge branch 'chan-fatfs' into fatfs-integration
[z180-stamp.git] / avr / getopt-min.c
1 /*
2 * Minimum getopt, original version was:
3 */
4
5 /*
6 getopt -- public domain version of standard System V routine
7
8 Strictly enforces the System V Command Syntax Standard;
9 provided by D A Gwyn of BRL for generic ANSI C implementations
10 */
11 /* $Id: getopt.c,v 1.2 1992/12/07 11:12:52 nickc Exp $ */
12
13 #include "common.h" /* definition of FLASH */
14 #include <string.h>
15
16 int optind = 0; /* next argv[] index */
17 char *optarg; /* option parameter if any */
18
19
20 int
21 getopt( /* returns letter, '?', EOF */
22 int argc, /* argument count from main */
23 char *const argv[], /* argument vector from main */
24 const FLASH char *optstring ) /* allowed args, e.g. "ab:c" */
25 {
26 static int sp; /* position within argument */
27 int osp; /* saved `sp' for param test */
28 int c; /* option letter */
29 const FLASH char *cp; /* -> option in `optstring' */
30
31 optarg = NULL;
32 if (optind == 0) { /* start a new argument scan */
33 optind = 1;
34 sp = 1;
35 }
36
37 if ( sp == 1 ) /* fresh argument */
38 {
39 if ( optind >= argc /* no more arguments */
40 || argv[optind][0] != '-' /* no more options */
41 || argv[optind][1] == '\0' /* not option; stdin */
42 )
43 return -1;
44 }
45
46 c = argv[optind][sp]; /* option letter */
47 osp = sp++; /* get ready for next letter */
48
49 if ( argv[optind][sp] == '\0' ) /* end of argument */
50 {
51 ++optind; /* get ready for next try */
52 sp = 1; /* beginning of next argument */
53 }
54
55 if ( c == ':' /* optstring syntax conflict */
56 || (cp = strchr_P( optstring, c )) == NULL /* not found */
57 )
58 return '?';
59
60 if ( cp[1] == ':' ) /* option takes parameter */
61 {
62 if ( osp != 1 )
63 return '?';
64
65 if ( sp != 1 ) /* reset by end of argument */
66 return '?';
67
68 if ( optind >= argc )
69 return '?';
70
71 optarg = argv[optind]; /* make parameter available */
72 ++optind; /* skip over parameter */
73 }
74
75 return c;
76 }