summaryrefslogtreecommitdiff
path: root/src/unistd/getopt.c
blob: a2dbea7bea9a33712a04898f4e52b9aab62dacfd (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
#include "sys/types.h"
#include "string.h"
#include "stdio.h"
#include <unistd.h>

int getopt(int argc, char * const argv[], const char *optstring)
{
	static int optchar = 0;
	char *cursor = NULL;

	if (optind == 0 || argv[optind][optchar] == '\0') {
		optind++;
		optchar = 0;
	}

	if (!strcmp(argv[optind], "--")) {
		optind++;
		return -1;
	}

	if (optchar == 0 && argv[optind][optchar] != '-') {
		return -1;
	}

	optchar++;

	printf("Checking %c\n", argv[optind][optchar]);

	cursor = strchr(optstring, argv[optind][optchar]);
	if (cursor) {
		if (cursor[1] == ':') {
			/* An option-argument is required */
			/* if (no arg) { */
			/*	optopt = *cursor; */
			/*	if (opterr) { */
			/*		fprintf(stderr, "%s: Missing argument to -%c\n", argv[0], *cursor); */
			/* 	} */
			/*	return optstring[0] == ':' ? ':' : '?'; */
			/* } */
			/* optarg = argv[++optind]; */
			/* optchar = 0; */
			/* optind++; */
		}
		return *cursor;
	}
	
	optopt = argv[optind][optchar];
	if (opterr) {
		fprintf(stderr, "%s: Invalid option -%c\n", *cursor);
	}
	return '?';
}

/*
POSIX(2)
*/