4 * Print a quotation from Zippy the Pinhead.
5 * Qux <Kaufman-David@Yale> March 6, 1986
7 * With dynamic memory allocation.
12 #include <../src/paths.h> /* For PATH_DATA. */
18 #define YOW_FILE "yow.lines"
22 #define rootrelativepath(rel) \
24 static char res[BUFSIZE], *p;\
25 strcpy (res, argv[0]);\
26 p = res + strlen (res);\
27 while (p != res && *p != '/' && *p != '\\' && *p != ':') p--;\
28 strcpy (p + 1, "../");\
33 char *malloc(), *realloc();
46 if (argc
> 2 && !strcmp (argv
[1], "-f"))
47 strcpy (file
, argv
[2]);
50 sprintf (file
, "%s%s", PATH_DATA
, YOW_FILE
);
52 sprintf (file
, "%s/%s", PATH_DATA
, YOW_FILE
);
55 if ((fp
= fopen(file
, "r")) == NULL
) {
56 fprintf(stderr
, "yow: ");
61 /* initialize random seed */
62 srand((int) (getpid() + time((long *) 0)));
71 static long header_len
;
73 #define AVG_LEN 40 /* average length of a quotation */
75 /* Sets len and header_len */
82 /* Get length of file */
83 /* Because the header (stuff before the first SEP) can be very long,
84 * thus biasing our search in favor of the first quotation in the file,
85 * we explicitly skip that. */
86 while ((c
= getc(fp
)) != SEP
) {
88 fprintf(stderr
, "yow: file contains no separators\n");
92 header_len
= ftell(fp
);
93 if (header_len
> AVG_LEN
)
94 header_len
-= AVG_LEN
; /* allow the first quotation to appear */
96 if (fseek(fp
, 0L, 2) == -1) {
100 len
= ftell(fp
) - header_len
;
104 /* go to a random place in the file and print the quotation there */
112 unsigned int bufsize
;
114 offset
= rand() % len
+ header_len
;
115 if (fseek(fp
, offset
, 0) == -1) {
120 /* Read until SEP, read next line, print it.
121 (Note that we will never print anything before the first separator.)
122 If we hit EOF looking for the first SEP, just recurse. */
123 while ((c
= getc(fp
)) != SEP
)
129 /* Skip leading whitespace, then read in a quotation.
130 If we hit EOF before we find a non-whitespace char, recurse. */
131 while (isspace(c
= getc(fp
)))
139 buf
= malloc(bufsize
);
140 if (buf
== (char *)0) {
141 fprintf(stderr
, "yow: virtual memory exhausted\n");
146 while ((c
= getc(fp
)) != SEP
&& c
!= EOF
) {
149 if (i
== bufsize
-1) {
150 /* Yow! Is this quotation too long yet? */
152 buf
= realloc(buf
, bufsize
);
153 if (buf
== (char *)0) {
154 fprintf(stderr
, "yow: virtual memory exhausted\n");