xref: /netbsd-src/games/fortune/strfile/strfile.c (revision 2980e352a13e8f0b545a366830c411e7a542ada8)
1 /*	$NetBSD: strfile.c,v 1.26 2008/07/20 01:03:21 lukem 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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #ifdef __NetBSD__
36 #include <sys/cdefs.h>
37 #ifndef lint
38 __COPYRIGHT("@(#) Copyright (c) 1989, 1993\
39  The Regents of the University of California.  All rights reserved.");
40 #endif /* not lint */
41 
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)strfile.c	8.1 (Berkeley) 5/31/93";
45 #else
46 __RCSID("$NetBSD: strfile.c,v 1.26 2008/07/20 01:03:21 lukem Exp $");
47 #endif
48 #endif /* not lint */
49 #endif /* __NetBSD__ */
50 
51 /* n.b.: this file is used at build-time - i.e. during build.sh. */
52 
53 # include	<sys/types.h>
54 # include	<sys/param.h>
55 # include	<ctype.h>
56 # include	<stdio.h>
57 # include	<stdlib.h>
58 # include	<string.h>
59 # include	<time.h>
60 # include	<unistd.h>
61 
62 # ifndef u_int32_t
63 # define u_int32_t	unsigned int
64 # endif
65 # include	"strfile.h"
66 
67 # ifndef MAXPATHLEN
68 # define	MAXPATHLEN	1024
69 # endif	/* MAXPATHLEN */
70 
71 u_int32_t
72 h2nl(u_int32_t h)
73 {
74         unsigned char c[4];
75         u_int32_t rv;
76 
77         c[0] = (h >> 24) & 0xff;
78         c[1] = (h >> 16) & 0xff;
79         c[2] = (h >>  8) & 0xff;
80         c[3] = (h >>  0) & 0xff;
81         memcpy(&rv, c, sizeof rv);
82 
83         return (rv);
84 }
85 
86 /*
87  *	This program takes a file composed of strings separated by
88  * lines starting with two consecutive delimiting character (default
89  * character is '%') and creates another file which consists of a table
90  * describing the file (structure from "strfile.h"), a table of seek
91  * pointers to the start of the strings, and the strings, each terminated
92  * by a null byte.  Usage:
93  *
94  *	% strfile [-iorsx] [ -cC ] sourcefile [ datafile ]
95  *
96  *	c - Change delimiting character from '%' to 'C'
97  *	s - Silent.  Give no summary of data processed at the end of
98  *	    the run.
99  *	o - order the strings in alphabetic order
100  *	i - if ordering, ignore case
101  *	r - randomize the order of the strings
102  *	x - set rotated bit
103  *
104  *		Ken Arnold	Sept. 7, 1978 --
105  *
106  *	Added ordering options.
107  */
108 
109 # define	TRUE	1
110 # define	FALSE	0
111 
112 # define	STORING_PTRS	(Oflag || Rflag)
113 # define	CHUNKSIZE	512
114 
115 # define	ALLOC(ptr,sz)	do { \
116 			if (ptr == NULL) \
117 				ptr = malloc(CHUNKSIZE * sizeof *ptr); \
118 			else if (((sz) + 1) % CHUNKSIZE == 0) \
119 				ptr = realloc(ptr, ((sz) + CHUNKSIZE) * sizeof *ptr); \
120 			if (ptr == NULL) \
121 				die("out of space"); \
122 		} while (0)
123 
124 typedef struct {
125 	char	first;
126 	off_t	pos;
127 } STR;
128 
129 char	*Infile		= NULL,		/* input file name */
130 	Outfile[MAXPATHLEN] = "",	/* output file name */
131 	Delimch		= '%';		/* delimiting character */
132 
133 int	Sflag		= FALSE;	/* silent run flag */
134 int	Oflag		= FALSE;	/* ordering flag */
135 int	Iflag		= FALSE;	/* ignore case flag */
136 int	Rflag		= FALSE;	/* randomize order flag */
137 int	Xflag		= FALSE;	/* set rotated bit */
138 long	Num_pts		= 0;		/* number of pointers/strings */
139 
140 off_t	*Seekpts;
141 
142 FILE	*Sort_1, *Sort_2;		/* pointers for sorting */
143 
144 STRFILE	Tbl;				/* statistics table */
145 
146 STR	*Firstch;			/* first chars of each string */
147 
148 #ifdef __GNUC__
149 #define NORETURN	__dead
150 #else
151 #define NORETURN
152 #endif
153 
154 #ifndef __dead /* not NetBSD, presumably */
155 #define __dead ;
156 #endif
157 
158 void	add_offset(FILE *, off_t);
159 int	cmp_str(const void *, const void *);
160 void	die(const char *) NORETURN;
161 void	dieperror(const char *, char *) NORETURN;
162 void	do_order(void);
163 void	fwrite_be_offt(off_t, FILE *);
164 void	getargs(int, char *[]);
165 int	main(int, char *[]);
166 void	randomize(void);
167 void	usage(void) NORETURN;
168 
169 
170 /*
171  * main:
172  *	Drive the sucker.  There are two main modes -- either we store
173  *	the seek pointers, if the table is to be sorted or randomized,
174  *	or we write the pointer directly to the file, if we are to stay
175  *	in file order.  If the former, we allocate and re-allocate in
176  *	CHUNKSIZE blocks; if the latter, we just write each pointer,
177  *	and then seek back to the beginning to write in the table.
178  */
179 int
180 main(ac, av)
181 	int	ac;
182 	char	*av[];
183 {
184 	char		*sp, dc;
185 	FILE		*inf, *outf;
186 	off_t		last_off, length, pos, *p;
187 	int		first, cnt;
188 	char		*nsp;
189 	STR		*fp;
190 	static char	string[257];
191 
192 	/* sanity test */
193 	if (sizeof(u_int32_t) != 4)
194 		die("sizeof(unsigned int) != 4");
195 
196 	getargs(ac, av);		/* evalute arguments */
197 	dc = Delimch;
198 	if ((inf = fopen(Infile, "r")) == NULL)
199 		dieperror("open `%s'", Infile);
200 
201 	if ((outf = fopen(Outfile, "w")) == NULL)
202 		dieperror("open `%s'", Outfile);
203 	if (!STORING_PTRS)
204 		(void) fseek(outf, sizeof Tbl, SEEK_SET);
205 
206 	/*
207 	 * Write the strings onto the file
208 	 */
209 
210 	Tbl.str_longlen = 0;
211 	Tbl.str_shortlen = (unsigned int) 0x7fffffff;
212 	Tbl.str_delim = dc;
213 	Tbl.str_version = VERSION;
214 	first = Oflag;
215 	add_offset(outf, ftell(inf));
216 	last_off = 0;
217 	do {
218 		sp = fgets(string, 256, inf);
219 		if (sp == NULL || (sp[0] == dc && sp[1] == '\n')) {
220 			pos = ftell(inf);
221 			length = pos - last_off - (sp ? strlen(sp) : 0);
222 			last_off = pos;
223 			if (!length)
224 				continue;
225 			add_offset(outf, pos);
226 			if ((off_t)Tbl.str_longlen < length)
227 				Tbl.str_longlen = length;
228 			if ((off_t)Tbl.str_shortlen > length)
229 				Tbl.str_shortlen = length;
230 			first = Oflag;
231 		}
232 		else if (first) {
233 			for (nsp = sp; !isalnum((unsigned char)*nsp); nsp++)
234 				continue;
235 			ALLOC(Firstch, Num_pts);
236 			fp = &Firstch[Num_pts - 1];
237 			if (Iflag && isupper((unsigned char)*nsp))
238 				fp->first = tolower((unsigned char)*nsp);
239 			else
240 				fp->first = *nsp;
241 			fp->pos = Seekpts[Num_pts - 1];
242 			first = FALSE;
243 		}
244 	} while (sp != NULL);
245 
246 	/*
247 	 * write the tables in
248 	 */
249 
250 	(void) fclose(inf);
251 
252 	if (Oflag)
253 		do_order();
254 	else if (Rflag)
255 		randomize();
256 
257 	if (Xflag)
258 		Tbl.str_flags |= STR_ROTATED;
259 
260 	if (!Sflag) {
261 		printf("\"%s\" created\n", Outfile);
262 		if (Num_pts == 2)
263 			puts("There was 1 string");
264 		else
265 			printf("There were %d strings\n", (int)(Num_pts - 1));
266 		printf("Longest string: %lu byte%s\n", (unsigned long)Tbl.str_longlen,
267 		       Tbl.str_longlen == 1 ? "" : "s");
268 		printf("Shortest string: %lu byte%s\n", (unsigned long)Tbl.str_shortlen,
269 		       Tbl.str_shortlen == 1 ? "" : "s");
270 	}
271 
272 	(void) fseek(outf, (off_t) 0, SEEK_SET);
273 	Tbl.str_version = h2nl(Tbl.str_version);
274 	Tbl.str_numstr = h2nl(Num_pts - 1);
275 	Tbl.str_longlen = h2nl(Tbl.str_longlen);
276 	Tbl.str_shortlen = h2nl(Tbl.str_shortlen);
277 	Tbl.str_flags = h2nl(Tbl.str_flags);
278 	(void) fwrite((char *) &Tbl, sizeof Tbl, 1, outf);
279 	if (STORING_PTRS) {
280 		for (p = Seekpts, cnt = Num_pts; cnt--; ++p)
281 			fwrite_be_offt(*p, outf);
282 	}
283 	fflush(outf);
284 	if (ferror(outf))
285 		dieperror("fwrite %s", Outfile);
286 	(void) fclose(outf);
287 	exit(0);
288 }
289 
290 /*
291  *	This routine evaluates arguments from the command line
292  */
293 void
294 getargs(argc, argv)
295 	int	argc;
296 	char	**argv;
297 {
298 	int	ch;
299 	extern	int optind;
300 	extern	char *optarg;
301 
302 	while ((ch = getopt(argc, argv, "c:iorsx")) != -1)
303 		switch(ch) {
304 		case 'c':			/* new delimiting char */
305 			Delimch = *optarg;
306 			if (!isascii(Delimch)) {
307 				printf("bad delimiting character: '\\%o\n'",
308 				       Delimch);
309 			}
310 			break;
311 		case 'i':			/* ignore case in ordering */
312 			Iflag++;
313 			break;
314 		case 'o':			/* order strings */
315 			Oflag++;
316 			break;
317 		case 'r':			/* randomize pointers */
318 			Rflag++;
319 			break;
320 		case 's':			/* silent */
321 			Sflag++;
322 			break;
323 		case 'x':			/* set the rotated bit */
324 			Xflag++;
325 			break;
326 		case '?':
327 		default:
328 			usage();
329 		}
330 	argv += optind;
331 
332 	if (*argv) {
333 		Infile = *argv;
334 		if (*++argv)
335 			(void) strcpy(Outfile, *argv);
336 	}
337 	if (!Infile) {
338 		puts("No input file name");
339 		usage();
340 	}
341 	if (*Outfile == '\0') {
342 		(void) strcpy(Outfile, Infile);
343 		(void) strcat(Outfile, ".dat");
344 	}
345 }
346 
347 void
348 usage()
349 {
350 	(void) fprintf(stderr,
351 	    "strfile [-iorsx] [-c char] sourcefile [datafile]\n");
352 	exit(1);
353 }
354 
355 void
356 die(str)
357 	const char *str;
358 {
359 	fprintf(stderr, "strfile: %s\n", str);
360 	exit(1);
361 }
362 
363 void
364 dieperror(fmt, file)
365 	const char *fmt;
366 	char *file;
367 {
368 	fprintf(stderr, "strfile: ");
369 	fprintf(stderr, fmt, file);
370 	fprintf(stderr, ": ");
371 	perror(NULL);
372 	exit(1);
373 }
374 
375 /*
376  * add_offset:
377  *	Add an offset to the list, or write it out, as appropriate.
378  */
379 void
380 add_offset(fp, off)
381 	FILE	*fp;
382 	off_t	off;
383 {
384 
385 	if (!STORING_PTRS) {
386 		fwrite_be_offt(off, fp);
387 	} else {
388 		ALLOC(Seekpts, Num_pts + 1);
389 		Seekpts[Num_pts] = off;
390 	}
391 	Num_pts++;
392 }
393 
394 /*
395  * do_order:
396  *	Order the strings alphabetically (possibly ignoring case).
397  */
398 void
399 do_order()
400 {
401 	int	i;
402 	off_t	*lp;
403 	STR	*fp;
404 
405 	Sort_1 = fopen(Infile, "r");
406 	Sort_2 = fopen(Infile, "r");
407 	qsort((char *) Firstch, (int) Tbl.str_numstr, sizeof *Firstch, cmp_str);
408 	i = Tbl.str_numstr;
409 	lp = Seekpts;
410 	fp = Firstch;
411 	while (i--)
412 		*lp++ = fp++->pos;
413 	(void) fclose(Sort_1);
414 	(void) fclose(Sort_2);
415 	Tbl.str_flags |= STR_ORDERED;
416 }
417 
418 int
419 cmp_str(vp1, vp2)
420 	const void *vp1, *vp2;
421 {
422 	const STR	*p1, *p2;
423 	int	c1, c2;
424 	int	n1, n2;
425 
426 	p1 = (const STR *)vp1;
427 	p2 = (const STR *)vp2;
428 
429 # define	SET_N(nf,ch)	(nf = (ch == '\n'))
430 # define	IS_END(ch,nf)	(ch == Delimch && nf)
431 
432 	c1 = p1->first;
433 	c2 = p2->first;
434 	if (c1 != c2)
435 		return c1 - c2;
436 
437 	(void) fseek(Sort_1, p1->pos, SEEK_SET);
438 	(void) fseek(Sort_2, p2->pos, SEEK_SET);
439 
440 	n1 = FALSE;
441 	n2 = FALSE;
442 	while (!isalnum(c1 = getc(Sort_1)) && c1 != '\0')
443 		SET_N(n1, c1);
444 	while (!isalnum(c2 = getc(Sort_2)) && c2 != '\0')
445 		SET_N(n2, c2);
446 
447 	while (!IS_END(c1, n1) && !IS_END(c2, n2)) {
448 		if (Iflag) {
449 			if (isupper(c1))
450 				c1 = tolower(c1);
451 			if (isupper(c2))
452 				c2 = tolower(c2);
453 		}
454 		if (c1 != c2)
455 			return c1 - c2;
456 		SET_N(n1, c1);
457 		SET_N(n2, c2);
458 		c1 = getc(Sort_1);
459 		c2 = getc(Sort_2);
460 	}
461 	if (IS_END(c1, n1))
462 		c1 = 0;
463 	if (IS_END(c2, n2))
464 		c2 = 0;
465 	return c1 - c2;
466 }
467 
468 /*
469  * randomize:
470  *	Randomize the order of the string table.  We must be careful
471  *	not to randomize across delimiter boundaries.  All
472  *	randomization is done within each block.
473  */
474 void
475 randomize()
476 {
477 	int	cnt, i;
478 	off_t	tmp;
479 	off_t	*sp;
480 
481 	srandom((int)(time((time_t *) NULL) + getpid()));
482 
483 	Tbl.str_flags |= STR_RANDOM;
484 	cnt = Tbl.str_numstr;
485 
486 	/*
487 	 * move things around randomly
488 	 */
489 
490 	for (sp = Seekpts; cnt > 0; cnt--, sp++) {
491 		i = random() % cnt;
492 		tmp = sp[0];
493 		sp[0] = sp[i];
494 		sp[i] = tmp;
495 	}
496 }
497 
498 /*
499  * fwrite_be_offt:
500  *	Write out the off paramater as a 64 bit big endian number
501  */
502 
503 void
504 fwrite_be_offt(off, f)
505 	off_t	 off;
506 	FILE	*f;
507 {
508 	int		i;
509 	unsigned char	c[8];
510 
511 	for (i = 7; i >= 0; i--) {
512 		c[i] = off & 0xff;
513 		off >>= 8;
514 	}
515 	fwrite(c, sizeof(c), 1, f);
516 }
517