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