summaryrefslogtreecommitdiffstats
path: root/src/misc/util/getopt.c
blob: 778c34d6c5d596d4468a89a82ae528b1473e9481 (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
77
78
79
80
81
82
83
84
/*
 * Revision Control Information
 *
 * /projects/hsis/CVS/utilities/util/getopt.c,v
 * rajeev
 * 1.3
 * 1995/08/08 22:41:22
 *
 */
/* LINTLIBRARY */

#include <stdio.h>
#include "util.h"


/*  File   : getopt.c
 *  Author : Henry Spencer, University of Toronto
 *  Updated: 28 April 1984
 *
 *  Changes: (R Rudell)
 *    changed index() to strchr();
 *    added getopt_reset() to reset the getopt argument parsing
 *
 *  Purpose: get option letter from argv.
 */

char *util_optarg;    /* Global argument pointer. */
int util_optind = 0;    /* Global argv index. */
static char *scan;


void
util_getopt_reset()
{
    util_optarg = 0;
    util_optind = 0;
    scan = 0;
}



int 
util_getopt(argc, argv, optstring)
int argc;
char *argv[];
char *optstring;
{
    register int c;
    register char *place;

    util_optarg = NIL(char);

    if (scan == NIL(char) || *scan == '\0') {
    if (util_optind == 0) util_optind++;
    if (util_optind >= argc) return EOF;
    place = argv[util_optind];
    if (place[0] != '-' || place[1] == '\0') return EOF;
    util_optind++;
    if (place[1] == '-' && place[2] == '\0') return EOF;
    scan = place+1;
    }

    c = *scan++;
    place = strchr(optstring, c);
    if (place == NIL(char) || c == ':') {
    (void) fprintf(stderr, "%s: unknown option %c\n", argv[0], c);
    return '?';
    }
    if (*++place == ':') {
    if (*scan != '\0') {
        util_optarg = scan;
        scan = NIL(char);
    } else {
        if (util_optind >= argc) {
        (void) fprintf(stderr, "%s: %c requires an argument\n", 
            argv[0], c);
        return '?';
        }
        util_optarg = argv[util_optind];
        util_optind++;
    }
    }
    return c;
}