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
18 #include <../src/sxe-paths.h> /* For PATH_DATA. */
20 #if __STDC__ || defined(STDC_HEADERS)
24 #include <time.h> /* for time() */
31 #define YOW_FILE "yow.lines"
35 void setup_yow(FILE * fp);
37 int main(int argc, char *argv[])
42 if (argc > 2 && !strcmp(argv[1], "-f")) {
43 strncpy(file, argv[2], sizeof(file)-1);
44 file[sizeof(file)-1]='\0';
48 int sz = snprintf(file, sizeof(file), "%s%s", PATH_DATA, YOW_FILE);
50 int sz = snprintf(file, sizeof(file), "%s/%s", PATH_DATA, YOW_FILE);
52 assert(sz>=0 && sz<sizeof(file));
53 #else /* !PATH_DATA */
55 "%s: the location of the \"%s\" file was not supplied at compile-time.\n\
56 You must supply it with the -f command-line option.\n",
62 if ((fp = fopen(file, "r")) == NULL) {
67 /* initialize random seed */
68 srand((int)(getpid() + time((time_t *) 0)));
77 static long header_len;
79 #define AVG_LEN 40 /* average length of a quotation */
81 /* Sets len and header_len */
82 void setup_yow(FILE * fp)
86 /* Get length of file */
87 /* Because the header (stuff before the first SEP) can be very long,
88 * thus biasing our search in favor of the first quotation in the file,
89 * we explicitly skip that. */
90 while ((c = getc(fp)) != SEP) {
92 fprintf(stderr, "File contains no separators.\n");
96 header_len = ftell(fp);
97 if (header_len > AVG_LEN)
98 header_len -= AVG_LEN; /* allow the first quotation to appear */
100 if (fseek(fp, 0L, 2) == -1) {
104 len = ftell(fp) - header_len;
107 /* go to a random place in the file and print the quotation there */
115 offset = rand() % len + header_len;
116 if (fseek(fp, offset, 0) == -1) {
121 /* Read until SEP, read next line, print it.
122 (Note that we will never print anything before the first separator.)
123 If we hit EOF looking for the first SEP, just recurse. */
124 while ((c = getc(fp)) != SEP)
130 /* Skip leading whitespace, then read in a quotation.
131 If we hit EOF before we find a non-whitespace char, recurse. */
132 while (isspace(c = getc(fp))) ;
139 buf = (char *)malloc(bufsize);
140 if (buf == (char *)0) {
141 fprintf(stderr, "can't allocate any memory\n");
146 while ((c = getc(fp)) != SEP && c != EOF) {
149 if (i == bufsize - 1) {
150 /* Yow! Is this quotation too long yet? */
152 buf = (char *)realloc(buf, bufsize);
153 if (buf == (char *)0) {
154 fprintf(stderr, "can't allocate more memory\n");