]>
git.cameronkatri.com Git - bsdgames-darwin.git/blob - larn/fortune.c
f410375da869a4809039270c2c97a7b935944a14
1 /* fortune.c Larn is copyrighted 1986 by Noah Morgan. */
8 * function to return a random fortune from the fortune file
10 static char *base
=0; /* pointer to the fortune text */
11 static char **flines
=0; /* array of pointers to each fortune */
12 static int fd
=0; /* true if we have load the fortune info */
13 static int nlines
=0; /* # lines in fortune database */
19 register int lines
,tmp
;
24 if ((fd
=open(file
,O_RDONLY
)) < 0) /* open the file */
25 return(0); /* can't find file */
27 /* find out how big fortune file is and get memory for it */
29 if ((fstat(fd
,&stat
) < 0) || ((base
=malloc(1+stat
.st_size
)) == 0))
31 close(fd
); fd
= -1; free((char*)base
); return(0); /* can't stat file */
34 /* read in the entire fortune file */
35 if (read(fd
,base
,stat
.st_size
) != stat
.st_size
)
37 close(fd
); fd
= -1; free((char*)base
); return(0); /* can't read file */
39 close(fd
); base
[stat
.st_size
]=0; /* final NULL termination */
41 /* count up all the lines (and NULL terminate) to know memory needs */
42 for (p
=base
,lines
=0; p
<base
+stat
.st_size
; p
++) /* count lines */
43 if (*p
== '\n') *p
=0,lines
++;
46 /* get memory for array of pointers to each fortune */
47 if ((flines
=(char**)malloc(nlines
*sizeof(char*))) == 0)
49 free((char*)base
); fd
= -1; return(0); /* malloc() failure */
52 /* now assign each pointer to a line */
53 for (p
=base
,tmp
=0; tmp
<nlines
; tmp
++)
55 flines
[tmp
]=p
; while (*p
++); /* advance to next line */
59 if (fd
> 2) /* if we have a database to look at */
60 return(flines
[rund((nlines
<=0)?1:nlines
)]);