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