kolibrios/programs/develop/ktcc/trunk/libc/stdlib/getopt.c
superturbocat2001 99103794f2 - Added simple function "getopt" in stdlib (tcc)
git-svn-id: svn://kolibrios.org@8380 a494cfbc-eb01-0410-851d-a64ba20cac60
2020-12-12 20:09:30 +00:00

64 lines
1.3 KiB
C

#include <stdio.h>
#include <string.h>
#include <getopt.h>
char *optarg = NULL; // global argument pointer
int optind = 0; // global argv index
int getopt(int argc, char *argv[], char *optstring) {
static char *next = NULL;
char c;
char *cp = NULL;
if (optind == 0)
next = NULL;
optarg = NULL;
if (next == NULL || *next == '\0') {
if (optind == 0)
optind++;
if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0') {
optarg = NULL;
if (optind < argc)
optarg = argv[optind];
return EOF;
}
if (strncmp(argv[optind], "--", 2) == 0) {
optind++;
optarg = NULL;
if (optind < argc)
optarg = argv[optind];
return EOF;
}
next = argv[optind];
next++; // skip past -
optind++;
}
c = *next++;
cp = strchr(optstring, c);
if (cp == NULL || c == ':')
return '?';
cp++;
if (*cp == ':') {
if (*next != '\0') {
optarg = next;
next = NULL;
}
else if (optind < argc) {
optarg = argv[optind];
optind++;
}
else {
return '?';
}
}
return c;
}