home *** CD-ROM | disk | FTP | other *** search
/ rtsi.com / 2014.01.www.rtsi.com.tar / www.rtsi.com / OS9 / TOP / USR / SRC / larn.t.Z / larn.t / fortune.c < prev    next >
Text File  |  1988-11-13  |  2KB  |  77 lines

  1. /* fortune.c         Larn is copyrighted 1986 by Noah Morgan. */
  2. #include <types.h>
  3. #include <stat.h>
  4.  
  5. #ifndef BSD4.1
  6. # ifndef OSK
  7. #include <fcntl.h>
  8. # else OSK
  9. # include <modes.h>
  10. # endif OSK
  11. #else BSD4.1
  12. #define O_RDONLY 0
  13. #endif BSD4.1
  14.  
  15. #include "header.h"
  16. /*
  17.  *    function to return a random fortune from the fortune file
  18.  */
  19. static char *base=0;    /* pointer to the fortune text */
  20. static char **flines=0;    /* array of pointers to each fortune */
  21. static int fd=0;        /* true if we have load the fortune info */
  22. static int nlines=0;    /* # lines in fortune database */
  23.  
  24. char *fortune(file)
  25.     char *file;
  26.     {
  27.     register char *p;
  28.     register int lines,tmp;
  29.     struct stat stat;
  30.     char *malloc();
  31.     if (fd==0)
  32.         {
  33. # ifndef OSK
  34.         if ((fd=open(file,O_RDONLY)) < 0)    /* open the file */
  35. # else OSK
  36.         if ((fd=open(file,S_IREAD)) < 0)
  37. # endif OSK
  38.             return(0); /* can't find file */
  39.  
  40.     /* find out how big fortune file is and get memory for it */
  41.         stat.st_size = 16384;
  42.         if ((fstat(fd,&stat) < 0) || ((base=malloc(1+stat.st_size)) == 0))
  43.             {
  44.             close(fd); fd= -1; free((char*)base); return(0);     /* can't stat file */
  45.             }
  46.  
  47.     /* read in the entire fortune file */
  48.         if (read(fd,base,stat.st_size) != stat.st_size)
  49.             {
  50.             close(fd); fd= -1; free((char*)base); return(0);     /* can't read file */
  51.             }
  52.         close(fd);  base[stat.st_size]=0;    /* final NULL termination */
  53.  
  54.     /* count up all the lines (and NULL terminate) to know memory needs */
  55.         for (p=base,lines=0; p<base+stat.st_size; p++) /* count lines */
  56.             if (*p == '\n') *p=0,lines++;
  57.         nlines = lines;
  58.  
  59.     /* get memory for array of pointers to each fortune */
  60.         if ((flines=(char**)malloc(nlines*sizeof(char*))) == 0)
  61.             {
  62.             free((char*)base); fd= -1; return(0); /* malloc() failure */
  63.             }
  64.  
  65.     /* now assign each pointer to a line */
  66.         for (p=base,tmp=0; tmp<nlines; tmp++)
  67.             {
  68.             flines[tmp]=p;  while (*p++); /* advance to next line */
  69.             }
  70.         }
  71.  
  72.     if (fd > 2)    /* if we have a database to look at */
  73.         return(flines[rund((nlines<=0)?1:nlines)]);
  74.     else 
  75.         return(0);
  76.     }
  77.