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