--- ray/src/common/wordfile.c 2003/10/22 02:06:34 2.12 +++ ray/src/common/wordfile.c 2016/03/23 15:14:33 2.18 @@ -1,5 +1,5 @@ #ifndef lint -static const char RCSid[] = "$Id: wordfile.c,v 2.12 2003/10/22 02:06:34 greg Exp $"; +static const char RCSid[] = "$Id: wordfile.c,v 2.18 2016/03/23 15:14:33 greg Exp $"; #endif /* * Load whitespace separated words from a file into an array. @@ -21,43 +21,61 @@ static const char RCSid[] = "$Id: wordfile.c,v 2.12 20 #include "standard.h" -#define MAXFLEN 8192 /* file must be smaller than this */ +#define MAXWLEN 4096 /* words must be shorter than this */ -extern char *bmalloc(); - int -wordfile(words, fname) /* get words from fname, put in words */ -char **words; -char *fname; +wordfile( /* get words from fname, put in words */ + char **words, + int nargs, + char *fname +) { + int wrdcnt = 0; + int n = 0; int fd; - char buf[MAXFLEN]; - register int n; + char buf[MAXWLEN]; /* load file into buffer */ - if (fname == NULL) + if (fname == NULL || !*fname) return(-1); /* no filename */ + if (nargs <= 1) + return(-1); if ((fd = open(fname, 0)) < 0) return(-1); /* open error */ - n = read(fd, buf, MAXFLEN); + words[0] = NULL; + while (nargs > 1 && (n += read(fd, buf+n, MAXWLEN-n)) > 0) { + int crem = 0; + if (n >= MAXWLEN) /* still something left? */ + while (!isspace(buf[--n])) { + if (n <= 0) /* one long word! */ + goto done; + ++crem; + } + buf[n] = '\0'; /* terminate & parse */ + n = wordstring(words, nargs, buf); + if (n < 0) { + wrdcnt = -1; /* memory error */ + break; + } + words += n; nargs -= n; + wrdcnt += n; + if ((n = crem) > 0) /* move remainder */ + memmove(buf, buf+MAXWLEN-crem, crem); + } +done: close(fd); - if (n < 0) /* read error */ - return(-1); - if (n == MAXFLEN) /* file too big, take what we can */ - while (!isspace(buf[--n])) - if (n <= 0) /* one long word! */ - return(-1); - buf[n] = '\0'; /* terminate */ - return(wordstring(words, buf)); /* wordstring does the rest */ + return(wrdcnt); } int -wordstring(avl, str) /* allocate and load argument list */ -char **avl; -char *str; +wordstring( /* allocate and load argument list */ + char **avl, + int nargs, + char *str +) { - register char *cp, **ap; + char *cp, **ap; if (str == NULL) return(-1); @@ -65,16 +83,17 @@ char *str; if (cp == NULL) /* ENOMEM */ return(-1); strcpy(cp, str); - ap = avl; /* parse into words */ - for ( ; ; ) { + /* parse into words */ + for (ap = avl; ap-avl < nargs-1; ap++) { while (isspace(*cp)) /* nullify spaces */ *cp++ = '\0'; if (!*cp) /* all done? */ break; - *ap++ = cp; /* add argument to list */ + *ap = cp; /* add argument to list */ while (*++cp && !isspace(*cp)) ; } + *cp = '\0'; /* terminates overflow */ *ap = NULL; return(ap - avl); }