]>
Commit | Line | Data |
---|---|---|
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 | ||
15 | int optind; /* next argv[] index */ | |
16 | char *optarg; /* option parameter if any */ | |
17 | ||
18 | ||
19 | int | |
20 | getopt( /* returns letter, '?', EOF */ | |
21 | int argc, /* argument count from main */ | |
22 | char *const argv[], /* argument vector from main */ | |
23 | const FLASH char *optstring ) /* allowed args, e.g. "ab:c" */ | |
24 | { | |
25 | static int sp; /* position within argument */ | |
26 | int osp; /* saved `sp' for param test */ | |
27 | int c; /* option letter */ | |
28 | const FLASH char *cp; /* -> option in `optstring' */ | |
29 | ||
30 | optarg = NULL; | |
31 | if (optind == 0) { /* start a new argument scan */ | |
32 | optind = 1; | |
33 | sp = 1; | |
34 | } | |
35 | ||
36 | if ( sp == 1 ) /* fresh argument */ | |
37 | { | |
38 | if ( optind >= argc /* no more arguments */ | |
39 | || argv[optind][0] != '-' /* no more options */ | |
40 | || argv[optind][1] == '\0' /* not option; stdin */ | |
41 | ) | |
42 | return -1; | |
43 | } | |
44 | ||
45 | c = argv[optind][sp]; /* option letter */ | |
46 | osp = sp++; /* get ready for next letter */ | |
47 | ||
48 | if ( argv[optind][sp] == '\0' ) /* end of argument */ | |
49 | { | |
50 | ++optind; /* get ready for next try */ | |
51 | sp = 1; /* beginning of next argument */ | |
52 | } | |
53 | ||
54 | if ( c == ':' /* optstring syntax conflict */ | |
55 | || (cp = strchr_P( optstring, c )) == NULL /* not found */ | |
56 | ) | |
57 | return '?'; | |
58 | ||
59 | if ( cp[1] == ':' ) /* option takes parameter */ | |
60 | { | |
61 | if ( osp != 1 ) | |
62 | return '?'; | |
63 | ||
64 | if ( sp != 1 ) /* reset by end of argument */ | |
65 | return '?'; | |
66 | ||
67 | if ( optind >= argc ) | |
68 | return '?'; | |
69 | ||
70 | optarg = argv[optind]; /* make parameter available */ | |
71 | ++optind; /* skip over parameter */ | |
72 | } | |
73 | ||
74 | return c; | |
75 | } |