Back to index

radiance  4R0+20100331
wordfile.c
Go to the documentation of this file.
00001 #ifndef lint
00002 static const char    RCSid[] = "$Id: wordfile.c,v 2.15 2005/06/10 16:42:11 greg Exp $";
00003 #endif
00004 /*
00005  * Load whitespace separated words from a file into an array.
00006  * Assume the passed pointer array is big enough to hold them all.
00007  *
00008  * External symbols declared in standard.h
00009  */
00010 
00011 #include "copyright.h"
00012 
00013 #include <ctype.h>
00014 #include <string.h>
00015 #include <stdio.h>
00016 #include <sys/types.h>
00017 #include <sys/stat.h>
00018 #include <fcntl.h>
00019 
00020 #include "platform.h"
00021 #include "standard.h"
00022 
00023 
00024 #ifndef MAXFLEN
00025 #define MAXFLEN             65536  /* file must be smaller than this */
00026 #endif
00027 
00028 
00029 int
00030 wordfile(words, fname)             /* get words from fname, put in words */
00031 char   **words;
00032 char   *fname;
00033 {
00034        int    fd;
00035        char   buf[MAXFLEN];
00036        register int  n;
00037                                    /* load file into buffer */
00038        if (fname == NULL)
00039               return(-1);                 /* no filename */
00040        if ((fd = open(fname, 0)) < 0)
00041               return(-1);                 /* open error */
00042        n = read(fd, buf, MAXFLEN);
00043        close(fd);
00044        if (n < 0)                         /* read error */
00045               return(-1);
00046        if (n == MAXFLEN)           /* file too big, take what we can */
00047               while (!isspace(buf[--n]))
00048                      if (n <= 0)          /* one long word! */
00049                             return(-1);
00050        buf[n] = '\0';                     /* terminate */
00051        return(wordstring(words, buf));    /* wordstring does the rest */
00052 }
00053 
00054 
00055 int
00056 wordstring(avl, str)               /* allocate and load argument list */
00057 char   **avl;
00058 char   *str;
00059 {
00060        register char *cp, **ap;
00061        
00062        if (str == NULL)
00063               return(-1);
00064        cp = bmalloc(strlen(str)+1);
00065        if (cp == NULL)                    /* ENOMEM */
00066               return(-1);
00067        strcpy(cp, str);
00068        ap = avl;            /* parse into words */
00069        for ( ; ; ) {
00070               while (isspace(*cp)) /* nullify spaces */
00071                      *cp++ = '\0';
00072               if (!*cp)            /* all done? */
00073                      break;
00074               *ap++ = cp;          /* add argument to list */
00075               while (*++cp && !isspace(*cp))
00076                      ;
00077        }
00078        *ap = NULL;
00079        return(ap - avl);
00080 }