4 * Print a quotation from Zippy the Pinhead.
5 * Qux <Kaufman-David@Yale> March 6, 1986
7 * With dynamic memory allocation.
10 /* Synched up with: FSF 19.28. */
12 #define DONT_ENCAPSULATE
17 #include <../src/sxe-paths.h> /* For PATH_DATA. */
19 #if __STDC__ || defined(STDC_HEADERS)
23 #include <time.h> /* for time() */
30 #define YOW_FILE "yow.lines"
34 void setup_yow(FILE * fp);
36 int main(int argc, char *argv[])
41 if (argc > 2 && !strcmp(argv[1], "-f"))
42 strcpy(file, argv[2]);
46 sprintf(file, "%s%s", PATH_DATA, YOW_FILE);
48 sprintf(file, "%s/%s", PATH_DATA, YOW_FILE);
50 #else /* !PATH_DATA */
53 "%s: the location of the \"%s\" file was not supplied at compile-time.\n\
54 You must supply it with the -f command-line option.\n",
60 if ((fp = fopen(file, "r")) == NULL) {
65 /* initialize random seed */
66 srand((int)(getpid() + time((time_t *) 0)));
75 static long header_len;
77 #define AVG_LEN 40 /* average length of a quotation */
79 /* Sets len and header_len */
80 void setup_yow(FILE * fp)
84 /* Get length of file */
85 /* Because the header (stuff before the first SEP) can be very long,
86 * thus biasing our search in favor of the first quotation in the file,
87 * we explicitly skip that. */
88 while ((c = getc(fp)) != SEP) {
90 fprintf(stderr, "File contains no separators.\n");
94 header_len = ftell(fp);
95 if (header_len > AVG_LEN)
96 header_len -= AVG_LEN; /* allow the first quotation to appear */
98 if (fseek(fp, 0L, 2) == -1) {
102 len = ftell(fp) - header_len;
105 /* go to a random place in the file and print the quotation there */
113 offset = rand() % len + header_len;
114 if (fseek(fp, offset, 0) == -1) {
119 /* Read until SEP, read next line, print it.
120 (Note that we will never print anything before the first separator.)
121 If we hit EOF looking for the first SEP, just recurse. */
122 while ((c = getc(fp)) != SEP)
128 /* Skip leading whitespace, then read in a quotation.
129 If we hit EOF before we find a non-whitespace char, recurse. */
130 while (isspace(c = getc(fp))) ;
137 buf = (char *)malloc(bufsize);
138 if (buf == (char *)0) {
139 fprintf(stderr, "can't allocate any memory\n");
144 while ((c = getc(fp)) != SEP && c != EOF) {
147 if (i == bufsize - 1) {
148 /* Yow! Is this quotation too long yet? */
150 buf = (char *)realloc(buf, bufsize);
151 if (buf == (char *)0) {
152 fprintf(stderr, "can't allocate more memory\n");