Home | History | Annotate | Line # | Download | only in strfile
strfile.c revision 1.15
      1 /*	$NetBSD: strfile.c,v 1.15 1999/12/07 23:07:39 jsm 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 #include <sys/cdefs.h>
     40 #ifndef lint
     41 __COPYRIGHT("@(#) Copyright (c) 1989, 1993\n\
     42 	The Regents of the University of California.  All rights reserved.\n");
     43 #endif /* not lint */
     44 
     45 #ifndef lint
     46 #if 0
     47 static char sccsid[] = "@(#)strfile.c	8.1 (Berkeley) 5/31/93";
     48 #else
     49 __RCSID("$NetBSD: strfile.c,v 1.15 1999/12/07 23:07:39 jsm Exp $");
     50 #endif
     51 #endif /* not lint */
     52 
     53 # include	<sys/types.h>
     54 # include	<sys/param.h>
     55 # include	<err.h>
     56 # include	<ctype.h>
     57 # include	<stdio.h>
     58 # include	<stdlib.h>
     59 # include	<string.h>
     60 # include	<time.h>
     61 # include	<unistd.h>
     62 # include	"strfile.h"
     63 
     64 # ifndef MAXPATHLEN
     65 # define	MAXPATHLEN	1024
     66 # endif	/* MAXPATHLEN */
     67 
     68 /*
     69  *	This program takes a file composed of strings seperated by
     70  * lines starting with two consecutive delimiting character (default
     71  * character is '%') and creates another file which consists of a table
     72  * describing the file (structure from "strfile.h"), a table of seek
     73  * pointers to the start of the strings, and the strings, each terminated
     74  * by a null byte.  Usage:
     75  *
     76  *	% strfile [-iorsx] [ -cC ] sourcefile [ datafile ]
     77  *
     78  *	c - Change delimiting character from '%' to 'C'
     79  *	s - Silent.  Give no summary of data processed at the end of
     80  *	    the run.
     81  *	o - order the strings in alphabetic order
     82  *	i - if ordering, ignore case
     83  *	r - randomize the order of the strings
     84  *	x - set rotated bit
     85  *
     86  *		Ken Arnold	Sept. 7, 1978 --
     87  *
     88  *	Added ordering options.
     89  */
     90 
     91 # define	TRUE	1
     92 # define	FALSE	0
     93 
     94 # define	STORING_PTRS	(Oflag || Rflag)
     95 # define	CHUNKSIZE	512
     96 
     97 # define	ALLOC(ptr,sz)	do { \
     98 			if (ptr == NULL) \
     99 				ptr = malloc((unsigned int) (CHUNKSIZE * sizeof *ptr)); \
    100 			else if (((sz) + 1) % CHUNKSIZE == 0) \
    101 				ptr = realloc((void *) ptr, ((unsigned int) ((sz) + CHUNKSIZE) * sizeof *ptr)); \
    102 			if (ptr == NULL) \
    103 				errx(1, "out of space"); \
    104 		} while (0)
    105 
    106 #ifdef NO_VOID
    107 # define	void	char
    108 #endif
    109 
    110 typedef struct {
    111 	char	first;
    112 	off_t	pos;
    113 } STR;
    114 
    115 char	*Infile		= NULL,		/* input file name */
    116 	Outfile[MAXPATHLEN] = "",	/* output file name */
    117 	Delimch		= '%';		/* delimiting character */
    118 
    119 int	Sflag		= FALSE;	/* silent run flag */
    120 int	Oflag		= FALSE;	/* ordering flag */
    121 int	Iflag		= FALSE;	/* ignore case flag */
    122 int	Rflag		= FALSE;	/* randomize order flag */
    123 int	Xflag		= FALSE;	/* set rotated bit */
    124 long	Num_pts		= 0;		/* number of pointers/strings */
    125 
    126 off_t	*Seekpts;
    127 
    128 FILE	*Sort_1, *Sort_2;		/* pointers for sorting */
    129 
    130 STRFILE	Tbl;				/* statistics table */
    131 
    132 STR	*Firstch;			/* first chars of each string */
    133 
    134 void	add_offset __P((FILE *, off_t));
    135 int	cmp_str __P((const void *, const void *));
    136 void	do_order __P((void));
    137 void	getargs __P((int, char *[]));
    138 int	main __P((int, char *[]));
    139 void	randomize __P((void));
    140 char   *unctrl __P((char));
    141 void	usage __P((void)) __attribute__((__noreturn__));
    142 
    143 
    144 /*
    145  * main:
    146  *	Drive the sucker.  There are two main modes -- either we store
    147  *	the seek pointers, if the table is to be sorted or randomized,
    148  *	or we write the pointer directly to the file, if we are to stay
    149  *	in file order.  If the former, we allocate and re-allocate in
    150  *	CHUNKSIZE blocks; if the latter, we just write each pointer,
    151  *	and then seek back to the beginning to write in the table.
    152  */
    153 int
    154 main(ac, av)
    155 	int	ac;
    156 	char	*av[];
    157 {
    158 	char		*sp, dc;
    159 	FILE		*inf, *outf;
    160 	off_t		last_off, length, pos, *p;
    161 	int		first, cnt;
    162 	char		*nsp;
    163 	STR		*fp;
    164 	static char	string[257];
    165 
    166 	getargs(ac, av);		/* evalute arguments */
    167 	dc = Delimch;
    168 	if ((inf = fopen(Infile, "r")) == NULL)
    169 		err(1, "open `%s'", Infile);
    170 
    171 	if ((outf = fopen(Outfile, "w")) == NULL)
    172 		err(1, "open `%s'", Outfile);
    173 	if (!STORING_PTRS)
    174 		(void) fseek(outf, sizeof Tbl, SEEK_SET);
    175 
    176 	/*
    177 	 * Write the strings onto the file
    178 	 */
    179 
    180 	Tbl.str_longlen = 0;
    181 	Tbl.str_shortlen = (unsigned int) 0xffffffff;
    182 	Tbl.str_delim = dc;
    183 	Tbl.str_version = VERSION;
    184 	first = Oflag;
    185 	add_offset(outf, ftell(inf));
    186 	last_off = 0;
    187 	do {
    188 		sp = fgets(string, 256, inf);
    189 		if (sp == NULL || (sp[0] == dc && sp[1] == '\n')) {
    190 			pos = ftell(inf);
    191 			length = pos - last_off - (sp ? strlen(sp) : 0);
    192 			last_off = pos;
    193 			if (!length)
    194 				continue;
    195 			add_offset(outf, pos);
    196 			if ((off_t)Tbl.str_longlen < length)
    197 				Tbl.str_longlen = length;
    198 			if ((off_t)Tbl.str_shortlen > length)
    199 				Tbl.str_shortlen = length;
    200 			first = Oflag;
    201 		}
    202 		else if (first) {
    203 			for (nsp = sp; !isalnum(*nsp); nsp++)
    204 				continue;
    205 			ALLOC(Firstch, Num_pts);
    206 			fp = &Firstch[Num_pts - 1];
    207 			if (Iflag && isupper(*nsp))
    208 				fp->first = tolower(*nsp);
    209 			else
    210 				fp->first = *nsp;
    211 			fp->pos = Seekpts[Num_pts - 1];
    212 			first = FALSE;
    213 		}
    214 	} while (sp != NULL);
    215 
    216 	/*
    217 	 * write the tables in
    218 	 */
    219 
    220 	(void) fclose(inf);
    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 %d strings\n", (int)(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 	(void) fseek(outf, (off_t) 0, SEEK_SET);
    243 	HTOBE32(Tbl.str_version);
    244 	Tbl.str_numstr = htobe32(Num_pts - 1);
    245 	HTOBE32(Tbl.str_longlen);
    246 	HTOBE32(Tbl.str_shortlen);
    247 	HTOBE32(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 			HTOBE64(*p);
    252 		(void) fwrite((char *) Seekpts, sizeof *Seekpts, (int) Num_pts, 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 void
    265 getargs(argc, argv)
    266 	int	argc;
    267 	char	**argv;
    268 {
    269 	int	ch;
    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 void
    317 usage()
    318 {
    319 	(void) fprintf(stderr,
    320 	    "strfile [-iorsx] [-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  */
    328 void
    329 add_offset(fp, off)
    330 	FILE	*fp;
    331 	off_t	off;
    332 {
    333 	off_t net;
    334 
    335 	if (!STORING_PTRS) {
    336 		net = htobe64(off);
    337 		fwrite(&net, 1, sizeof net, fp);
    338 	} else {
    339 		ALLOC(Seekpts, Num_pts + 1);
    340 		Seekpts[Num_pts] = off;
    341 	}
    342 	Num_pts++;
    343 }
    344 
    345 /*
    346  * do_order:
    347  *	Order the strings alphabetically (possibly ignoring case).
    348  */
    349 void
    350 do_order()
    351 {
    352 	int	i;
    353 	off_t	*lp;
    354 	STR	*fp;
    355 
    356 	Sort_1 = fopen(Infile, "r");
    357 	Sort_2 = fopen(Infile, "r");
    358 	qsort((char *) Firstch, (int) Tbl.str_numstr, sizeof *Firstch, cmp_str);
    359 	i = Tbl.str_numstr;
    360 	lp = Seekpts;
    361 	fp = Firstch;
    362 	while (i--)
    363 		*lp++ = fp++->pos;
    364 	(void) fclose(Sort_1);
    365 	(void) fclose(Sort_2);
    366 	Tbl.str_flags |= STR_ORDERED;
    367 }
    368 
    369 /*
    370  * cmp_str:
    371  *	Compare two strings in the file
    372  */
    373 char *
    374 unctrl(c)
    375 	char c;
    376 {
    377 	static char	buf[3];
    378 
    379 	if (isprint(c)) {
    380 		buf[0] = c;
    381 		buf[1] = '\0';
    382 	}
    383 	else if (c == 0177) {
    384 		buf[0] = '^';
    385 		buf[1] = '?';
    386 	}
    387 	else {
    388 		buf[0] = '^';
    389 		buf[1] = c + 'A' - 1;
    390 	}
    391 	return buf;
    392 }
    393 
    394 int
    395 cmp_str(vp1, vp2)
    396 	const void *vp1, *vp2;
    397 {
    398 	const STR	*p1, *p2;
    399 	int	c1, c2;
    400 	int	n1, n2;
    401 
    402 	p1 = (const STR *)vp1;
    403 	p2 = (const STR *)vp2;
    404 
    405 # define	SET_N(nf,ch)	(nf = (ch == '\n'))
    406 # define	IS_END(ch,nf)	(ch == Delimch && nf)
    407 
    408 	c1 = p1->first;
    409 	c2 = p2->first;
    410 	if (c1 != c2)
    411 		return c1 - c2;
    412 
    413 	(void) fseek(Sort_1, p1->pos, SEEK_SET);
    414 	(void) fseek(Sort_2, p2->pos, SEEK_SET);
    415 
    416 	n1 = FALSE;
    417 	n2 = FALSE;
    418 	while (!isalnum(c1 = getc(Sort_1)) && c1 != '\0')
    419 		SET_N(n1, c1);
    420 	while (!isalnum(c2 = getc(Sort_2)) && c2 != '\0')
    421 		SET_N(n2, c2);
    422 
    423 	while (!IS_END(c1, n1) && !IS_END(c2, n2)) {
    424 		if (Iflag) {
    425 			if (isupper(c1))
    426 				c1 = tolower(c1);
    427 			if (isupper(c2))
    428 				c2 = tolower(c2);
    429 		}
    430 		if (c1 != c2)
    431 			return c1 - c2;
    432 		SET_N(n1, c1);
    433 		SET_N(n2, c2);
    434 		c1 = getc(Sort_1);
    435 		c2 = getc(Sort_2);
    436 	}
    437 	if (IS_END(c1, n1))
    438 		c1 = 0;
    439 	if (IS_END(c2, n2))
    440 		c2 = 0;
    441 	return c1 - c2;
    442 }
    443 
    444 /*
    445  * randomize:
    446  *	Randomize the order of the string table.  We must be careful
    447  *	not to randomize across delimiter boundaries.  All
    448  *	randomization is done within each block.
    449  */
    450 void
    451 randomize()
    452 {
    453 	int	cnt, i;
    454 	off_t	tmp;
    455 	off_t	*sp;
    456 
    457 	srandom((int)(time((time_t *) NULL) + getpid()));
    458 
    459 	Tbl.str_flags |= STR_RANDOM;
    460 	cnt = Tbl.str_numstr;
    461 
    462 	/*
    463 	 * move things around randomly
    464 	 */
    465 
    466 	for (sp = Seekpts; cnt > 0; cnt--, sp++) {
    467 		i = random() % cnt;
    468 		tmp = sp[0];
    469 		sp[0] = sp[i];
    470 		sp[i] = tmp;
    471 	}
    472 }
    473