]> granicus.if.org Git - fortune-mod/blob - fortune-mod/util/strfile.c
appveyor fix #1: better windows/etc. compat
[fortune-mod] / fortune-mod / util / strfile.c
1 /*      $NetBSD: strfile.c,v 1.3 1995/03/23 08:28:47 cgd Exp $  */
2
3 /*-
4  * Copyright (c) 1989, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Ken Arnold.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38
39 /*
40  * Changes, September 1995, to make the damn thing actually sort instead
41  * of just pretending.  Amy A. Lewis
42  *
43  * And lots more.
44  *
45  * Fixed the special cases of %^J% (an empty fortune), no 'separator' at
46  * the end of the file, and a trailing newline at the end of the file, all
47  * of which produced total ballsup at one point or another.
48  *
49  * This included adding a routine to go back and write over the last pointer
50  * written or stored, for the case of an empty fortune.
51  *
52  * unstr also had to be modified (well, for *lots* of reasons, but this was
53  * one) to be certain to put the delimiters in the right places.
54  */
55
56 #include "fortune-mod-common.h"
57
58 /*
59  *    This program takes a file composed of strings separated by
60  * lines containing only the delimiting character (the default
61  * character is '%') and creates another file which consists of a table
62  * describing the file (structure from "strfile.h"), a table of seek
63  * pointers to the start of the strings, and the strings, each terminated
64  * by a null byte.  Usage:
65  *
66  *      % strfile [-iorsx] [ -cC ] sourcefile [ datafile ]
67  *
68  *      c - Change delimiting character from '%' to 'C'
69  *      s - Silent.  Give no summary of data processed at the end of
70  *          the run.
71  *      o - order the strings in alphabetic order
72  *      i - if ordering, ignore case
73  *      r - randomize the order of the strings
74  *      x - set rotated bit
75  *
76  *              Ken Arnold      Sept. 7, 1978 --
77  *
78  *      Added ordering options.
79  *
80  * Made ordering options do more than set the bloody flag, September 95 A. Lewis
81  *
82  * Always make sure that your loop control variables aren't set to bloody
83  * *zero* before distributing the bloody code, all right?
84  *
85  */
86
87 #define CHUNKSIZE 512
88
89 #define ALLOC(ptr, sz)                                                         \
90     {                                                                          \
91         if (!ptr)                                                              \
92             ptr = malloc((unsigned int)(CHUNKSIZE * sizeof *ptr));             \
93         else if (((sz) + 1) % CHUNKSIZE == 0)                                  \
94             ptr = realloc((void *)ptr,                                         \
95                 ((unsigned int)((sz) + CHUNKSIZE) * sizeof *ptr));             \
96         if (!ptr)                                                              \
97         {                                                                      \
98             fprintf(stderr, "out of space\n");                                 \
99             exit(1);                                                           \
100         }                                                                      \
101     }
102
103 typedef struct
104 {
105     char first;
106     int32_t pos;
107 } STR;
108
109 static char delimiter_char = '%';
110
111 static bool Sflag = false; /* silent run flag */
112 static bool Oflag = false; /* ordering flag */
113 static bool Iflag = false; /* ignore case flag */
114 static bool Rflag = false; /* randomize order flag */
115 static bool Xflag = false; /* set rotated bit */
116 static long Num_pts = 0;   /* number of pointers/strings */
117
118 static bool storing_ptrs(void) { return (Oflag || Rflag); }
119
120 static int32_t *Seekpts;
121
122 static FILE *Sort_1, *Sort_2; /* pointers for sorting */
123
124 static STRFILE Tbl; /* statistics table */
125
126 static STR *Firstch; /* first chars of each string */
127
128 static void __attribute__((noreturn)) usage(void)
129 {
130     fprintf(stderr, "%s", "strfile [-iorsx] [-c char] sourcefile [datafile]\n");
131     exit(1);
132 }
133
134 #include "fortune-util-set-outfn.h"
135
136 /*
137  *    This routine evaluates arguments from the command line
138  */
139 static void getargs(int argc, char **argv)
140 {
141     int ch;
142
143     while ((ch = getopt(argc, argv, "c:iorsx")) != EOF)
144         switch (ch)
145         {
146         case 'c': /* new delimiting char */
147             delimiter_char = *optarg;
148             if (!isascii(delimiter_char))
149             {
150                 printf("bad delimiting character: '\\%o\n'",
151                     (unsigned int)delimiter_char);
152             }
153             break;
154         case 'i': /* ignore case in ordering */
155             Iflag = true;
156             break;
157         case 'o': /* order strings */
158             Oflag = true;
159             break;
160         case 'r': /* randomize pointers */
161             Rflag = true;
162             break;
163         case 's': /* silent */
164             Sflag = true;
165             break;
166         case 'x': /* set the rotated bit */
167             Xflag = true;
168             break;
169         case '?':
170         default:
171             usage();
172         }
173     argv += optind;
174
175     if (*argv)
176     {
177         input_filename = *argv;
178         set_output_filename(*++argv);
179     }
180     if (!input_filename)
181     {
182         puts("No input file name");
183         usage();
184     }
185     if (*output_filename == '\0')
186     {
187         if (strlen(input_filename) > MAXPATHLEN - 10)
188         {
189             puts("input file name too long!");
190             usage();
191         }
192         snprintf(
193             output_filename, COUNT(output_filename), "%s.dat", input_filename);
194     }
195 }
196
197 /*
198  * add_offset:
199  *      Add an offset to the list, or write it out, as appropriate.
200  */
201 static void add_offset(FILE *fp, int32_t off)
202 {
203     if (!storing_ptrs())
204     {
205         uint32_t net;
206         net = htonl((uint32_t)off);
207         fwrite(&net, 1, sizeof net, fp);
208     }
209     else
210     {
211         ALLOC(Seekpts, Num_pts + 1);
212         Seekpts[Num_pts] = off;
213     }
214     Num_pts++;
215 }
216
217 /*
218  * fix_last_offset:
219  *     Used when we have two separators in a row.
220  */
221 static void fix_last_offset(FILE *const fp, const int32_t off)
222 {
223     if (!storing_ptrs())
224     {
225         uint32_t net = htonl((uint32_t)off);
226         fseek(fp, -(long)(sizeof net), SEEK_CUR);
227         fwrite(&net, 1, sizeof net, fp);
228     }
229     else
230     {
231         Seekpts[Num_pts - 1] = off;
232     }
233 }
234
235 /*
236  * cmp_str:
237  *      Compare two strings in the file
238  */
239 static int cmp_str(const void *v1, const void *v2)
240 {
241 #define SET_N(nf, ch) (nf = (ch == '\n'))
242 #define IS_END(ch, nf) (ch == delimiter_char && nf)
243
244     const STR *p1 = (const STR *)v1;
245     const STR *p2 = (const STR *)v2;
246     int c1 = p1->first;
247     int c2 = p2->first;
248     if (c1 != c2)
249     {
250         return c1 - c2;
251     }
252
253     fseek(Sort_1, p1->pos, SEEK_SET);
254     fseek(Sort_2, p2->pos, SEEK_SET);
255
256     bool n1 = false;
257     bool n2 = false;
258     while (!isalnum(c1 = getc(Sort_1)) && c1 != '\0')
259         SET_N(n1, c1);
260     while (!isalnum(c2 = getc(Sort_2)) && c2 != '\0')
261         SET_N(n2, c2);
262
263     while (!IS_END(c1, n1) && !IS_END(c2, n2))
264     {
265         if (Iflag)
266         {
267             if (isupper(c1))
268                 c1 = tolower(c1);
269             if (isupper(c2))
270                 c2 = tolower(c2);
271         }
272         if (c1 != c2)
273         {
274             return c1 - c2;
275         }
276         SET_N(n1, c1);
277         SET_N(n2, c2);
278         c1 = getc(Sort_1);
279         c2 = getc(Sort_2);
280     }
281     if (IS_END(c1, n1))
282     {
283         c1 = 0;
284     }
285     if (IS_END(c2, n2))
286     {
287         c2 = 0;
288     }
289     return c1 - c2;
290 }
291
292 /*
293  * do_order:
294  *      Order the strings alphabetically (possibly ignoring case).
295  */
296 static void do_order(void)
297 {
298     Sort_1 = fopen(input_filename, "r");
299     Sort_2 = fopen(input_filename, "r");
300     qsort(
301         (char *)Firstch, (size_t)((int)Num_pts - 1), sizeof *Firstch, cmp_str);
302     /*      i = Tbl.str_numstr;
303      * Fucking brilliant.  Tbl.str_numstr was initialized to zero, and is still
304      * zero
305      */
306     long i = Num_pts - 1;
307     int32_t *lp = Seekpts;
308     STR *fp = Firstch;
309     while (i--)
310     {
311         *lp++ = fp++->pos;
312     }
313     fclose(Sort_1);
314     fclose(Sort_2);
315     Tbl.str_flags |= STR_ORDERED;
316 }
317
318 /*
319  * randomize:
320  *      Randomize the order of the string table.  We must be careful
321  *      not to randomize across delimiter boundaries.  All
322  *      randomization is done within each block.
323  */
324 static void randomize(void)
325 {
326     srandom((unsigned int)(time((time_t *)NULL) + getpid()));
327
328     Tbl.str_flags |= STR_RANDOM;
329     /*      cnt = Tbl.str_numstr;
330      * See comment above.  Isn't this stuff distributed worldwide?  How
331      * embarrassing!
332      */
333     int cnt = (int)Num_pts;
334
335     /*
336      * move things around randomly
337      */
338
339     int32_t *sp = Seekpts;
340     for (; cnt > 0; cnt--, sp++)
341     {
342         const int i = random() % cnt;
343         const int32_t tmp = sp[0];
344         sp[0] = sp[i];
345         sp[i] = tmp;
346     }
347 }
348
349 /*
350  * main:
351  *      Drive the sucker.  There are two main modes -- either we store
352  *      the seek pointers, if the table is to be sorted or randomized,
353  *      or we write the pointer directly to the file, if we are to stay
354  *      in file order.  If the former, we allocate and re-allocate in
355  *      CHUNKSIZE blocks; if the latter, we just write each pointer,
356  *      and then seek back to the beginning to write in the table.
357  */
358 int main(int ac, char **av)
359 {
360     char *sp;
361     FILE *inf, *outf;
362     bool len_was_set = false;
363
364     getargs(ac, av); /* evalute arguments */
365     if (!(inf = fopen(input_filename, "r")))
366     {
367         perror(input_filename);
368         exit(1);
369     }
370
371     if (!(outf = fopen(output_filename, "w")))
372     {
373         perror(output_filename);
374         exit(1);
375     }
376     if (!storing_ptrs())
377     {
378         (void)fseek(outf, sizeof Tbl, SEEK_SET);
379     }
380
381     /*
382      * Write the strings onto the file
383      */
384
385     Tbl.str_longlen = 0;
386     Tbl.str_shortlen = (unsigned int)0xffffffff;
387     Tbl.str_delim = (uint8_t)delimiter_char;
388     Tbl.str_version = STRFILE_VERSION;
389     bool first = Oflag;
390     add_offset(outf, (int32_t)ftell(inf));
391     int32_t last_off = 0;
392     do
393     {
394         char string[257];
395         sp = fgets(string, 256, inf);
396         if ((!sp) || STR_ENDSTRING(sp, Tbl))
397         {
398             const int32_t pos = (int32_t)ftell(inf);
399             const int32_t length =
400                 pos - last_off - (int32_t)(sp ? strlen(sp) : 0);
401             if (!length)
402             /* Here's where we go back and fix things, if the
403              * 'fortune' just read was the null string.
404              * We had to make the assignment of last_off slightly
405              * redundant to achieve this.
406              */
407             {
408                 if (pos - last_off == 2)
409                 {
410                     fix_last_offset(outf, pos);
411                 }
412                 last_off = pos;
413                 continue;
414             }
415             last_off = pos;
416             add_offset(outf, pos);
417             if (!len_was_set)
418             {
419                 Tbl.str_longlen = (uint32_t)length;
420                 Tbl.str_shortlen = (uint32_t)length;
421                 len_was_set = true;
422             }
423             else
424             {
425                 if ((int)Tbl.str_longlen < length)
426                 {
427                     Tbl.str_longlen = (uint32_t)length;
428                 }
429                 if (Tbl.str_shortlen > (uint32_t)length)
430                 {
431                     Tbl.str_shortlen = (uint32_t)length;
432                 }
433             }
434             first = Oflag;
435         }
436         else if (first)
437         {
438             char *nsp = sp;
439             for (; !isalnum(*nsp); ++nsp)
440             {
441             }
442             ALLOC(Firstch, Num_pts);
443             STR *const fp = &Firstch[Num_pts - 1];
444             fp->first =
445                 ((Iflag && isupper(*nsp)) ? ((char)tolower(*nsp)) : (*nsp));
446             fp->pos = Seekpts[Num_pts - 1];
447             first = false;
448         }
449     } while (sp);
450
451     /*
452      * write the tables in
453      */
454
455     fclose(inf);
456
457     if (Oflag)
458     {
459         do_order();
460     }
461     else if (Rflag)
462     {
463         randomize();
464     }
465
466     if (Xflag)
467     {
468         Tbl.str_flags |= STR_ROTATED;
469     }
470
471     if (!Sflag)
472     {
473         printf("\"%s\" created\n", output_filename);
474         if (Num_pts == 1)
475         {
476             puts("There was no string");
477         }
478         else
479         {
480             if (Num_pts == 2)
481             {
482                 puts("There was 1 string");
483             }
484             else
485             {
486                 printf("There were %ld strings\n", Num_pts - 1);
487             }
488             printf("Longest string: %lu byte%s\n",
489                 (unsigned long)(Tbl.str_longlen),
490                 Tbl.str_longlen == 1 ? "" : "s");
491             printf("Shortest string: %lu byte%s\n",
492                 (unsigned long)(Tbl.str_shortlen),
493                 Tbl.str_shortlen == 1 ? "" : "s");
494         }
495     }
496
497     fseek(outf, (off_t)0, SEEK_SET);
498     Tbl.str_version = htonl(Tbl.str_version);
499     Tbl.str_numstr = htonl((uint32_t)(Num_pts - 1));
500     /* Look, Ma!  After using the variable three times, let's store
501      * something in it!
502      */
503     Tbl.str_longlen = htonl(Tbl.str_longlen);
504     Tbl.str_shortlen = htonl(Tbl.str_shortlen);
505     Tbl.str_flags = htonl(Tbl.str_flags);
506     fwrite(&Tbl.str_version, sizeof Tbl.str_version, 1, outf);
507     fwrite(&Tbl.str_numstr, sizeof Tbl.str_numstr, 1, outf);
508     fwrite(&Tbl.str_longlen, sizeof Tbl.str_longlen, 1, outf);
509     fwrite(&Tbl.str_shortlen, sizeof Tbl.str_shortlen, 1, outf);
510     fwrite(&Tbl.str_flags, sizeof Tbl.str_flags, 1, outf);
511     fwrite(Tbl.stuff, sizeof Tbl.stuff, 1, outf);
512     if (storing_ptrs())
513     {
514         int cnt = (int)Num_pts;
515         for (int32_t *p = Seekpts; cnt--; ++p)
516         {
517             *p = (int32_t)htonl((uint32_t)*p);
518             fwrite(p, sizeof *p, 1, outf);
519         }
520     }
521     fclose(outf);
522     exit(0);
523 }