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