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