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"
33 static void yow(FILE * fp);
34 static void setup_yow(FILE * fp);
37 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 */
56 "%s: the location of the \"%s\" file was not supplied at compile-time.\n\
57 You must supply it with the -f command-line option.\n",
63 if ((fp = fopen(file, "r")) == NULL) {
68 /* initialize random seed */
69 srand((int)(getpid() + time((time_t *) 0)));
78 static long header_len;
80 #define AVG_LEN 40 /* average length of a quotation */
82 /* Sets len and header_len */
88 /* Get length of file */
89 /* Because the header (stuff before the first SEP) can be very long,
90 * thus biasing our search in favor of the first quotation in the file,
91 * we explicitly skip that. */
92 while ((c = getc(fp)) != SEP) {
94 fprintf(stderr, "File contains no separators.\n");
98 header_len = ftell(fp);
99 if (header_len > AVG_LEN)
100 header_len -= AVG_LEN; /* allow the first quotation to appear */
102 if (fseek(fp, 0L, 2) == -1) {
106 len = ftell(fp) - header_len;
109 /* go to a random place in the file and print the quotation there */
118 offset = rand() % len + header_len;
119 if (fseek(fp, offset, 0) == -1) {
124 /* Read until SEP, read next line, print it.
125 (Note that we will never print anything before the first separator.)
126 If we hit EOF looking for the first SEP, just recurse. */
127 while ((c = getc(fp)) != SEP)
133 /* Skip leading whitespace, then read in a quotation.
134 If we hit EOF before we find a non-whitespace char, recurse. */
135 while (isspace(c = getc(fp))) ;
142 buf = (char *)malloc(bufsize);
143 if (buf == (char *)0) {
144 fprintf(stderr, "can't allocate any memory\n");
149 while ((c = getc(fp)) != SEP && c != EOF) {
152 if (i == bufsize - 1) {
153 /* Yow! Is this quotation too long yet? */
155 buf = (char *)realloc(buf, bufsize);
156 if (buf == (char *)0) {
157 fprintf(stderr, "can't allocate more memory\n");