ack/lang/cem/libcc.ansi/misc/getopt.c

73 lines
1.2 KiB
C
Raw Normal View History

1989-12-18 14:40:54 +00:00
/*
* getopt - parse command-line options
*/
1994-06-24 14:02:31 +00:00
/* $Id$ */
1989-12-18 14:40:54 +00:00
2018-06-21 20:33:47 +00:00
#include <stdio.h>
#include <string.h>
1989-12-18 14:40:54 +00:00
2018-06-21 20:33:47 +00:00
#define ERR(s, c) \
if (opterr) \
{ \
fputs(argv[0], stderr); \
fputs(s, stderr); \
fputc(c, stderr); \
fputc('\n', stderr); \
}
1989-12-18 14:40:54 +00:00
2018-06-21 20:33:47 +00:00
int opterr = 1;
int optind = 1;
int optopt;
char* optarg;
1989-12-18 14:40:54 +00:00
2018-06-21 20:33:47 +00:00
int getopt(int argc, char** argv, char* opts)
1989-12-18 14:40:54 +00:00
{
static int sp = 1;
register c;
2018-06-21 20:33:47 +00:00
register char* cp;
1989-12-18 14:40:54 +00:00
if (sp == 1)
2018-06-21 20:33:47 +00:00
if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0')
1989-12-18 14:40:54 +00:00
return EOF;
2018-06-21 20:33:47 +00:00
else if (!strcmp(argv[optind], "--"))
{
1989-12-18 14:40:54 +00:00
optind++;
return EOF;
}
optopt = c = argv[optind][sp];
2018-06-21 20:33:47 +00:00
if (c == ':' || (cp = strchr(opts, c)) == NULL)
{
ERR(": illegal option -- ", c);
if (argv[optind][++sp] == '\0')
{
1989-12-18 14:40:54 +00:00
optind++;
sp = 1;
}
return '?';
}
2018-06-21 20:33:47 +00:00
if (*++cp == ':')
{
if (argv[optind][sp + 1] != '\0')
optarg = &argv[optind++][sp + 1];
else if (++optind >= argc)
{
ERR(": option requires an argument -- ", c);
1989-12-18 14:40:54 +00:00
sp = 1;
return '?';
2018-06-21 20:33:47 +00:00
}
else
1989-12-18 14:40:54 +00:00
optarg = argv[optind++];
sp = 1;
2018-06-21 20:33:47 +00:00
}
else
{
if (argv[optind][++sp] == '\0')
{
1989-12-18 14:40:54 +00:00
sp = 1;
optind++;
}
optarg = NULL;
}
return c;
}