home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Phoenix Heaven Sunny 2
/
APPARE2.BIN
/
oh_towns
/
dic
/
src
/
getopt.c
< prev
next >
Wrap
C/C++ Source or Header
|
1995-06-20
|
3KB
|
166 lines
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "getopt.h"
extern char *progname();
char *optarg = "";
int optind = 1;
static char *optstr = NULL;
static char *optcmp(str, ptn)
char *str;
char *ptn;
{
while ( *ptn != '\0' ) {
if ( *str != *ptn )
return NULL;
str++;
ptn++;
}
return str;
}
int getopt_long(ac, av, tab)
int ac;
char *av[];
struct option *tab;
{
int n;
char *p;
for ( ; ; ) {
if ( optstr != NULL && *optstr != '\0' ) {
for ( n = 0 ; tab[n].str != NULL ; n++ ) {
if ( tab[n].opt == *optstr ) {
optstr++;
if ( tab[n].pfg != 0 ) {
if ( *optstr == '=' )
optstr++;
if ( *optstr != '\0' )
optarg = optstr;
else if ( optind < ac && *av[optind] != '-' )
optarg = av[optind++];
else if ( tab[n].pfg != 2 ) {
fprintf(stderr,
"%s: option `-%c' requires an argument\n",
progname(av[0]), tab[n].opt);
optstr = NULL;
return '\0';
} else
optarg = NULL;
optstr = NULL;
}
return tab[n].opt;
}
}
fprintf(stderr, "%s: unrecognized option `-%c'\n",
progname(av[0]), *optstr);
return *(optstr++);
}
if ( optind >= ac || *av[optind] != '-' )
return EOF;
optstr = av[optind++] + 1;
if ( *optstr == '-' ) { /* -- */
optstr++;
for ( n = 0 ; tab[n].str != NULL ; n++ ) {
if ( (p = optcmp(optstr, tab[n].str)) != NULL ) {
if ( tab[n].pfg != 0 ) {
optstr = p;
if ( *optstr == '=' )
optstr++;
if ( *optstr != '\0' )
optarg = optstr;
else if ( optind < ac && *av[optind] != '-' )
optarg = av[optind++];
else if ( tab[n].pfg != 2 ) {
fprintf(stderr,
"%s: option `--%s' requires an argument\n",
progname(av[0]), tab[n].str);
optstr = NULL;
return '\0';
} else
optarg = NULL;
} else if ( *p != '\0' )
continue;
optstr = NULL;
return tab[n].opt;
}
}
fprintf(stderr, "%s: unrecognized option `--%s'\n",
progname(av[0]), optstr);
optstr = NULL;
return '\0';
}
}
}
void insert_opt(int *acp, char ***avp, int no, char *opt)
{
int n;
int ac;
char **av;
char **nv;
char *p;
if ( opt == NULL )
return;
ac = *acp;
av = *avp;
p = opt;
while ( *p != '\0' ) {
while ( isspace(*p) )
p++;
if ( *p == '\0' )
break;
ac++;
while ( *p != '\0' && !isspace(*p) )
p++;
}
if ( *acp == ac )
return;
if ( (nv = (char **)malloc(sizeof(char *) * ac + 1)) == NULL )
return;
if ( (p = (char *)malloc(strlen(opt) + 1)) == NULL )
return;
strcpy(p, opt);
for ( n = 0 ; n < no ; n++ )
nv[n] = av[n];
while ( *p != '\0' ) {
while ( isspace(*p) )
p++;
if ( *p == '\0' )
break;
nv[n++] = p;
while ( *p != '\0' && !isspace(*p) )
p++;
if ( *p != '\0' )
*(p++) = '\0';
}
ac = *acp;
while ( no < ac )
nv[n++] = av[no++];
nv[n] = NULL;
*acp = n;
*avp = nv;
}