]> cloudbase.mooo.com Git - z180-stamp.git/blame - avr/getopt-min.c
Add copyright notice
[z180-stamp.git] / avr / getopt-min.c
CommitLineData
41d36f28
L
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
35edb766
L
13#include "common.h" /* definition of FLASH */
14#include <string.h>
41d36f28
L
15
16int optind = 1; /* next argv[] index */
17char *optarg; /* option parameter if any */
18
19
20int
21getopt( /* 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 = 1; /* 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
33 if ( sp == 1 ) /* fresh argument */
34 {
35 if ( optind >= argc /* no more arguments */
36 || argv[optind][0] != '-' /* no more options */
37 || argv[optind][1] == '\0' /* not option; stdin */
38 )
cd5ee544 39 return -1;
41d36f28 40 }
35edb766 41
41d36f28
L
42 c = argv[optind][sp]; /* option letter */
43 osp = sp++; /* get ready for next letter */
44
45 if ( argv[optind][sp] == '\0' ) /* end of argument */
46 {
47 ++optind; /* get ready for next try */
48 sp = 1; /* beginning of next argument */
49 }
50
51 if ( c == ':' /* optstring syntax conflict */
52 || (cp = strchr_P( optstring, c )) == NULL /* not found */
53 )
54 return '?';
55
56 if ( cp[1] == ':' ) /* option takes parameter */
57 {
58 if ( osp != 1 )
59 return '?';
60
61 if ( sp != 1 ) /* reset by end of argument */
62 return '?';
63
64 if ( optind >= argc )
65 return '?';
66
67 optarg = argv[optind]; /* make parameter available */
68 ++optind; /* skip over parameter */
69 }
70
71 return c;
72}