summaryrefslogtreecommitdiff
path: root/tools/getopt.c
blob: 36a9bc174d4aca5e5c016b5df66dfcf405dda31f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int             optind = 1;
char            *optarg = (char *)NULL;

int	getopt (int argc, char **argv, char *optstring)
{
    int		cur_option;		/* Current option		*/
    char	*cp;			/* Character pointer		*/
    static int	GetOptionPosition = 1;

    if (GetOptionPosition == 1)
    {

/* Check for out of range, correct start character and not single */

	if ((optind >= argc) || (*argv[optind] != '-') || !argv[optind][1])
	    return EOF;

	if (!strcmp (argv[optind], "--"))
	    return EOF;
    }

/* Get the current character from the current argument vector */

    cur_option = argv[optind][GetOptionPosition];

/* Validate it */

    if ((cur_option == ':') ||
	((cp = strchr (optstring, cur_option)) == (char *)NULL))
    {

/* Move to the next offset */

	if (!argv[optind][++GetOptionPosition])
	{
	    optind++;
	    GetOptionPosition = 1;
	}

	return '?';
    }

/* Parameters following ? */

    optarg = (char *)NULL;

    if (*(++cp) == ':')
    {
	if (argv[optind][GetOptionPosition + 1])
	    optarg = &argv[optind++][GetOptionPosition + 1];

	else if (++optind >= argc)
	{
	    optarg = (char *)NULL;
	    GetOptionPosition = 1;
	    return '?';
	}

	else
	    optarg = argv[optind++];

	GetOptionPosition = 1;
    }

    else if (!argv[optind][++GetOptionPosition])
    {
	GetOptionPosition = 1;
	optind++;
    }

    return cur_option;
}