File: xgetopt.c

package info (click to toggle)
foo2zjs 20171202dfsg0-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 9,320 kB
  • sloc: ansic: 40,789; xml: 12,512; sh: 7,385; makefile: 1,705; objc: 573; tcl: 173; perl: 102; python: 8
file content (75 lines) | stat: -rw-r--r-- 1,726 bytes parent folder | download | duplicates (16)
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
/*
    getopt.c 

*/

#include <errno.h>
#include <string.h>
#include <stdio.h>
 
int     xoptind = 1;    /* index of which argument is next  */
char   *xoptarg;        /* pointer to argument of current option */
int     xopterr = 0;    /* allow error message  */
 
static  char   *letP = NULL;    /* remember next option char's location */
char    SW = '-';				/* DOS switch character, either '-' or '/' */

/*
  Parse the command line options, System V style.

  Standard option syntax is:

    option ::= SW [optLetter]* [argLetter space* argument]

*/

int xgetopt(int argc, char *argv[], char *optionS)
{
    unsigned char ch;
    char *optP;

    if (SW == 0) {
        SW = '/';
    }

    if (argc > xoptind) {
        if (letP == NULL) {
            if ((letP = argv[xoptind]) == NULL ||
                *(letP++) != SW)  goto gopEOF;
            if (*letP == SW) {
                xoptind++;  goto gopEOF;
            }
        }
        if (0 == (ch = *(letP++))) {
            xoptind++;  goto gopEOF;
        }
        if (':' == ch  ||  (optP = strchr(optionS, ch)) == NULL)
            goto gopError;
        if (':' == *(++optP)) {
            xoptind++;
            if (0 == *letP) {
                if (argc <= xoptind)  goto  gopError;
                letP = argv[xoptind++];
            }
            xoptarg = letP;
            letP = NULL;
        } else {
            if (0 == *letP) {
                xoptind++;
                letP = NULL;
            }
            xoptarg = NULL;
        }
        return ch;
    }
gopEOF:
    xoptarg = letP = NULL;
    return EOF;

gopError:
    xoptarg = NULL;
    errno  = EINVAL;
    if (xopterr)
        perror ("get command line option");
    return ('?');
}