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