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"
34 static void yow(FILE * fp);
35 static void setup_yow(FILE * fp);
37 #define xstrncpy(d_,s_,l_) \
41 strncat((dst_),(s_),(l_)-1); \
46 main(int argc, char *argv[])
51 if (argc > 2 && !strcmp(argv[1], "-f")) {
52 xstrncpy(file, argv[2], sizeof(file)-1);
53 file[sizeof(file)-1]='\0';
57 int sz = snprintf(file, sizeof(file), "%s%s", PATH_DATA, YOW_FILE);
59 int sz = snprintf(file, sizeof(file), "%s/%s", PATH_DATA, YOW_FILE);
61 assert(sz>=0 && sz<sizeof(file));
62 #else /* !PATH_DATA */
64 "%s: the location of the \"%s\" file was not supplied at compile-time.\n\
65 You must supply it with the -f command-line option.\n",
71 if ((fp = fopen(file, "r")) == NULL) {
76 /* initialize random seed */
77 srand((int)(getpid() + time((time_t *) 0)));
86 static long header_len;
88 #define AVG_LEN 40 /* average length of a quotation */
90 /* Sets len and header_len */
96 /* Get length of file */
97 /* Because the header (stuff before the first SEP) can be very long,
98 * thus biasing our search in favor of the first quotation in the file,
99 * we explicitly skip that. */
100 while ((c = getc(fp)) != SEP) {
102 fprintf(stderr, "File contains no separators.\n");
106 header_len = ftell(fp);
107 if (header_len > AVG_LEN)
108 header_len -= AVG_LEN; /* allow the first quotation to appear */
110 if (fseek(fp, 0L, 2) == -1) {
114 len = ftell(fp) - header_len;
117 /* go to a random place in the file and print the quotation there */
126 offset = rand() % len + header_len;
127 if (fseek(fp, offset, 0) == -1) {
132 /* Read until SEP, read next line, print it.
133 (Note that we will never print anything before the first separator.)
134 If we hit EOF looking for the first SEP, just recurse. */
135 while ((c = getc(fp)) != SEP)
141 /* Skip leading whitespace, then read in a quotation.
142 If we hit EOF before we find a non-whitespace char, recurse. */
143 while (isspace(c = getc(fp))) ;
150 buf = (char *)malloc(bufsize);
151 if (buf == (char *)0) {
152 fprintf(stderr, "can't allocate any memory\n");
157 while ((c = getc(fp)) != SEP && c != EOF) {
160 if (i == bufsize - 1) {
161 /* Yow! Is this quotation too long yet? */
163 buf = (char *)realloc(buf, bufsize);
164 if (buf == (char *)0) {
165 fprintf(stderr, "can't allocate more memory\n");