Home | History | Annotate | Line # | Download | only in join
join.c revision 1.19
      1 /*	$NetBSD: join.c,v 1.19 2000/06/10 19:21:05 mycroft Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1991 The Regents of the University of California.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Steve Hayman of Indiana University, Michiro Hikida and David
      9  * Goodenough.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the University of
     22  *	California, Berkeley and its contributors.
     23  * 4. Neither the name of the University nor the names of its contributors
     24  *    may be used to endorse or promote products derived from this software
     25  *    without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     37  * SUCH DAMAGE.
     38  */
     39 
     40 #include <sys/cdefs.h>
     41 #ifndef lint
     42 __COPYRIGHT(
     43     "@(#) Copyright (c) 1991 The Regents of the University of California.\n\
     44  All rights reserved.\n");
     45 #endif /* not lint */
     46 
     47 #ifndef lint
     48 #if 0
     49 static char sccsid[] = "from: @(#)join.c	5.1 (Berkeley) 11/18/91";
     50 #else
     51 __RCSID("$NetBSD: join.c,v 1.19 2000/06/10 19:21:05 mycroft Exp $");
     52 #endif
     53 #endif /* not lint */
     54 
     55 #include <sys/types.h>
     56 #include <ctype.h>
     57 #include <err.h>
     58 #include <errno.h>
     59 #include <stdio.h>
     60 #include <stdlib.h>
     61 #include <unistd.h>
     62 #include <string.h>
     63 #include <unistd.h>
     64 
     65 /*
     66  * There's a structure per input file which encapsulates the state of the
     67  * file.  We repeatedly read lines from each file until we've read in all
     68  * the consecutive lines from the file with a common join field.  Then we
     69  * compare the set of lines with an equivalent set from the other file.
     70  */
     71 typedef struct {
     72 	char *line;		/* line */
     73 	u_long linealloc;	/* line allocated count */
     74 	char **fields;		/* line field(s) */
     75 	u_long fieldcnt;	/* line field(s) count */
     76 	u_long fieldalloc;	/* line field(s) allocated count */
     77 } LINE;
     78 
     79 typedef struct {
     80 	FILE *fp;		/* file descriptor */
     81 	u_long joinf;		/* join field (-1, -2, -j) */
     82 	int unpair;		/* output unpairable lines (-a) */
     83 	int number;		/* 1 for file 1, 2 for file 2 */
     84 
     85 	LINE *set;		/* set of lines with same field */
     86 	u_long pushback;	/* line on the stack */
     87 	u_long setcnt;		/* set count */
     88 	u_long setalloc;	/* set allocated count */
     89 } INPUT;
     90 INPUT input1 = { NULL, 0, 0, 1, NULL, -1, 0, 0, },
     91       input2 = { NULL, 0, 0, 1, NULL, -1, 0, 0, };
     92 
     93 typedef struct {
     94 	u_long	fileno;		/* file number */
     95 	u_long	fieldno;	/* field number */
     96 } OLIST;
     97 OLIST *olist;			/* output field list */
     98 u_long olistcnt;		/* output field list count */
     99 u_long olistalloc;		/* output field allocated count */
    100 
    101 int joinout = 1;		/* show lines with matched join fields (-v) */
    102 int needsep;			/* need separator character */
    103 int spans = 1;			/* span multiple delimiters (-t) */
    104 char *empty;			/* empty field replacement string (-e) */
    105 char *tabchar = " \t";		/* delimiter characters (-t) */
    106 
    107 int  cmp __P((LINE *, u_long, LINE *, u_long));
    108 void enomem __P((void));
    109 void fieldarg __P((char *));
    110 void joinlines __P((INPUT *, INPUT *));
    111 int  main __P((int, char **));
    112 void obsolete __P((char **));
    113 void outfield __P((LINE *, u_long));
    114 void outoneline __P((INPUT *, LINE *));
    115 void outtwoline __P((INPUT *, LINE *, INPUT *, LINE *));
    116 void slurp __P((INPUT *));
    117 void usage __P((void));
    118 
    119 int
    120 main(argc, argv)
    121 	int argc;
    122 	char *argv[];
    123 {
    124 	INPUT *F1, *F2;
    125 	int aflag, ch, cval, vflag;
    126 	char *end;
    127 
    128 	F1 = &input1;
    129 	F2 = &input2;
    130 
    131 	aflag = vflag = 0;
    132 	obsolete(argv);
    133 	while ((ch = getopt(argc, argv, "\01a:e:j:1:2:o:t:v:")) != -1) {
    134 		switch (ch) {
    135 		case '\01':
    136 			aflag = 1;
    137 			F1->unpair = F2->unpair = 1;
    138 			break;
    139 		case '1':
    140 			if ((F1->joinf = strtol(optarg, &end, 10)) < 1) {
    141 				warnx("-1 option field number less than 1");
    142 				usage();
    143 			}
    144 			if (*end) {
    145 				warnx("illegal field number -- %s", optarg);
    146 				usage();
    147 			}
    148 			--F1->joinf;
    149 			break;
    150 		case '2':
    151 			if ((F2->joinf = strtol(optarg, &end, 10)) < 1) {
    152 				warnx("-2 option field number less than 1");
    153 				usage();
    154 			}
    155 			if (*end) {
    156 				warnx("illegal field number -- %s", optarg);
    157 				usage();
    158 			}
    159 			--F2->joinf;
    160 			break;
    161 		case 'a':
    162 			aflag = 1;
    163 			switch(strtol(optarg, &end, 10)) {
    164 			case 1:
    165 				F1->unpair = 1;
    166 				break;
    167 			case 2:
    168 				F2->unpair = 1;
    169 				break;
    170 			default:
    171 				warnx("-a option file number not 1 or 2");
    172 				usage();
    173 				break;
    174 			}
    175 			if (*end) {
    176 				warnx("illegal file number -- %s", optarg);
    177 				usage();
    178 			}
    179 			break;
    180 		case 'e':
    181 			empty = optarg;
    182 			break;
    183 		case 'j':
    184 			if ((F1->joinf = F2->joinf =
    185 			    strtol(optarg, &end, 10)) < 1) {
    186 				warnx("-j option field number less than 1");
    187 				usage();
    188 			}
    189 			if (*end) {
    190 				warnx("illegal field number -- %s", optarg);
    191 				usage();
    192 			}
    193 			--F1->joinf;
    194 			--F2->joinf;
    195 			break;
    196 		case 'o':
    197 			fieldarg(optarg);
    198 			break;
    199 		case 't':
    200 			spans = 0;
    201 			if (strlen(tabchar = optarg) != 1) {
    202 				warnx("illegal tab character specification");
    203 				usage();
    204 			}
    205 			break;
    206 		case 'v':
    207 			vflag = 1;
    208 			joinout = 0;
    209 			switch(strtol(optarg, &end, 10)) {
    210 			case 1:
    211 				F1->unpair = 1;
    212 				break;
    213 			case 2:
    214 				F2->unpair = 1;
    215 				break;
    216 			default:
    217 				warnx("-v option file number not 1 or 2");
    218 				usage();
    219 				break;
    220 			}
    221 			if (*end) {
    222 				warnx("illegal file number -- %s", optarg);
    223 				usage();
    224 			}
    225 			break;
    226 		case '?':
    227 		default:
    228 			usage();
    229 		}
    230 	}
    231 	argc -= optind;
    232 	argv += optind;
    233 
    234 	if (aflag && vflag)
    235 		errx(1, "-a and -v options mutually exclusive");
    236 
    237 	if (argc != 2)
    238 		usage();
    239 
    240 	/* Open the files; "-" means stdin. */
    241 	if (!strcmp(*argv, "-"))
    242 		F1->fp = stdin;
    243 	else if ((F1->fp = fopen(*argv, "r")) == NULL)
    244 		err(1, "%s", *argv);
    245 	++argv;
    246 	if (!strcmp(*argv, "-"))
    247 		F2->fp = stdin;
    248 	else if ((F2->fp = fopen(*argv, "r")) == NULL)
    249 		err(1, "%s", *argv);
    250 	if (F1->fp == stdin && F2->fp == stdin)
    251 		errx(1, "only one input file may be stdin");
    252 
    253 	slurp(F1);
    254 	slurp(F2);
    255 	while (F1->setcnt && F2->setcnt) {
    256 		cval = cmp(F1->set, F1->joinf, F2->set, F2->joinf);
    257 		if (cval == 0) {
    258 			/* Oh joy, oh rapture, oh beauty divine! */
    259 			if (joinout)
    260 				joinlines(F1, F2);
    261 			slurp(F1);
    262 			slurp(F2);
    263 		} else if (cval < 0) {
    264 			/* File 1 takes the lead... */
    265 			if (F1->unpair)
    266 				joinlines(F1, NULL);
    267 			slurp(F1);
    268 		} else {
    269 			/* File 2 takes the lead... */
    270 			if (F2->unpair)
    271 				joinlines(F2, NULL);
    272 			slurp(F2);
    273 		}
    274 	}
    275 
    276 	/*
    277 	 * Now that one of the files is used up, optionally output any
    278 	 * remaining lines from the other file.
    279 	 */
    280 	if (F1->unpair)
    281 		while (F1->setcnt) {
    282 			joinlines(F1, NULL);
    283 			slurp(F1);
    284 		}
    285 	if (F2->unpair)
    286 		while (F2->setcnt) {
    287 			joinlines(F2, NULL);
    288 			slurp(F2);
    289 		}
    290 	exit(0);
    291 }
    292 
    293 void
    294 slurp(F)
    295 	INPUT *F;
    296 {
    297 	LINE *lp;
    298 	LINE tmp;
    299 	size_t len;
    300 	int cnt;
    301 	char *bp, *fieldp;
    302 
    303 	/*
    304 	 * Read all of the lines from an input file that have the same
    305 	 * join field.
    306 	 */
    307 	for (F->setcnt = 0;; ++F->setcnt) {
    308 		/*
    309 		 * If we're out of space to hold line structures, allocate
    310 		 * more.  Initialize the structure so that we know that this
    311 		 * is new space.
    312 		 */
    313 		if (F->setcnt == F->setalloc) {
    314 			cnt = F->setalloc;
    315 			if (F->setalloc == 0)
    316 				F->setalloc = 64;
    317 			else
    318 				F->setalloc <<= 1;
    319 			if ((F->set = realloc(F->set,
    320 			    F->setalloc * sizeof(LINE))) == NULL)
    321 				enomem();
    322 			memset(F->set + cnt, 0,
    323 			    (F->setalloc - cnt) * sizeof(LINE));
    324 		}
    325 
    326 		/*
    327 		 * Get any pushed back line, else get the next line.  Allocate
    328 		 * space as necessary.  If taking the line from the stack swap
    329 		 * the two structures so that we don't lose the allocated space.
    330 		 * This could be avoided by doing another level of indirection,
    331 		 * but it's probably okay as is.
    332 		 */
    333 		lp = &F->set[F->setcnt];
    334 		if (F->pushback != -1) {
    335 			tmp = F->set[F->setcnt];
    336 			F->set[F->setcnt] = F->set[F->pushback];
    337 			F->set[F->pushback] = tmp;
    338 			F->pushback = -1;
    339 			continue;
    340 		}
    341 		if ((bp = fgetln(F->fp, &len)) == NULL)
    342 			return;
    343 		if (lp->linealloc <= len + 1) {
    344 			if (lp->linealloc == 0)
    345 				lp->linealloc = 128;
    346 			while (lp->linealloc <= len + 1)
    347 				lp->linealloc <<= 1;
    348 			if ((lp->line = realloc(lp->line,
    349 			    lp->linealloc * sizeof(char))) == NULL)
    350 				enomem();
    351 		}
    352 		memmove(lp->line, bp, len);
    353 
    354 		/* Replace trailing newline, if it exists. */
    355 		if (bp[len - 1] == '\n')
    356 			lp->line[len - 1] = '\0';
    357 		else
    358 			lp->line[len] = '\0';
    359 		bp = lp->line;
    360 
    361 		/* Split the line into fields, allocate space as necessary. */
    362 		lp->fieldcnt = 0;
    363 		while ((fieldp = strsep(&bp, tabchar)) != NULL) {
    364 			if (spans && *fieldp == '\0')
    365 				continue;
    366 			if (lp->fieldcnt == lp->fieldalloc) {
    367 				if (lp->fieldalloc == 0)
    368 					lp->fieldalloc = 16;
    369 				else
    370 					lp->fieldalloc <<= 1;
    371 				if ((lp->fields = realloc(lp->fields,
    372 				    lp->fieldalloc * sizeof(char *))) == NULL)
    373 					enomem();
    374 			}
    375 			lp->fields[lp->fieldcnt++] = fieldp;
    376 		}
    377 
    378 		/* See if the join field value has changed. */
    379 		if (F->setcnt && cmp(lp, F->joinf, lp - 1, F->joinf)) {
    380 			F->pushback = F->setcnt;
    381 			break;
    382 		}
    383 	}
    384 }
    385 
    386 int
    387 cmp(lp1, fieldno1, lp2, fieldno2)
    388 	LINE *lp1, *lp2;
    389 	u_long fieldno1, fieldno2;
    390 {
    391 
    392 	if (lp1->fieldcnt <= fieldno1)
    393 		return (lp2->fieldcnt <= fieldno2 ? 0 : 1);
    394 	if (lp2->fieldcnt <= fieldno2)
    395 		return (-1);
    396 	return (strcmp(lp1->fields[fieldno1], lp2->fields[fieldno2]));
    397 }
    398 
    399 void
    400 joinlines(F1, F2)
    401 	INPUT *F1, *F2;
    402 {
    403 	int cnt1, cnt2;
    404 
    405 	/*
    406 	 * Output the results of a join comparison.  The output may be from
    407 	 * either file 1 or file 2 (in which case the first argument is the
    408 	 * file from which to output) or from both.
    409 	 */
    410 	if (F2 == NULL) {
    411 		for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
    412 			outoneline(F1, &F1->set[cnt1]);
    413 		return;
    414 	}
    415 	for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
    416 		for (cnt2 = 0; cnt2 < F2->setcnt; ++cnt2)
    417 			outtwoline(F1, &F1->set[cnt1], F2, &F2->set[cnt2]);
    418 }
    419 
    420 void
    421 outoneline(F, lp)
    422 	INPUT *F;
    423 	LINE *lp;
    424 {
    425 	int cnt;
    426 
    427 	/*
    428 	 * Output a single line from one of the files, according to the
    429 	 * join rules.  This happens when we are writing unmatched single
    430 	 * lines.  Output empty fields in the right places.
    431 	 */
    432 	if (olist)
    433 		for (cnt = 0; cnt < olistcnt; ++cnt) {
    434 			if (olist[cnt].fileno == F->number)
    435 				outfield(lp, olist[cnt].fieldno);
    436 		}
    437 	else
    438 		for (cnt = 0; cnt < lp->fieldcnt; ++cnt)
    439 			outfield(lp, cnt);
    440 	(void)printf("\n");
    441 	if (ferror(stdout))
    442 		err(1, "stdout");
    443 	needsep = 0;
    444 }
    445 
    446 void
    447 outtwoline(F1, lp1, F2, lp2)
    448 	INPUT *F1, *F2;
    449 	LINE *lp1, *lp2;
    450 {
    451 	int cnt;
    452 
    453 	/* Output a pair of lines according to the join list (if any). */
    454 	if (olist) {
    455 		for (cnt = 0; cnt < olistcnt; ++cnt)
    456 			if (olist[cnt].fileno == 1)
    457 				outfield(lp1, olist[cnt].fieldno);
    458 			else /* if (olist[cnt].fileno == 2) */
    459 				outfield(lp2, olist[cnt].fieldno);
    460 	} else {
    461 		/*
    462 		 * Output the join field, then the remaining fields from F1
    463 		 * and F2.
    464 		 */
    465 		outfield(lp1, F1->joinf);
    466 		for (cnt = 0; cnt < lp1->fieldcnt; ++cnt)
    467 			if (F1->joinf != cnt)
    468 				outfield(lp1, cnt);
    469 		for (cnt = 0; cnt < lp2->fieldcnt; ++cnt)
    470 			if (F2->joinf != cnt)
    471 				outfield(lp2, cnt);
    472 	}
    473 	(void)printf("\n");
    474 	if (ferror(stdout))
    475 		err(1, "stdout");
    476 	needsep = 0;
    477 }
    478 
    479 void
    480 outfield(lp, fieldno)
    481 	LINE *lp;
    482 	u_long fieldno;
    483 {
    484 	if (needsep++)
    485 		(void)printf("%c", *tabchar);
    486 	if (!ferror(stdout)) {
    487 		if (lp->fieldcnt <= fieldno) {
    488 			if (empty != NULL)
    489 				(void)printf("%s", empty);
    490 		} else {
    491 			if (*lp->fields[fieldno] == '\0')
    492 				return;
    493 			(void)printf("%s", lp->fields[fieldno]);
    494 		}
    495 	}
    496 	if (ferror(stdout))
    497 		err(1, "stdout");
    498 }
    499 
    500 /*
    501  * Convert an output list argument "2.1, 1.3, 2.4" into an array of output
    502  * fields.
    503  */
    504 void
    505 fieldarg(option)
    506 	char *option;
    507 {
    508 	u_long fieldno;
    509 	char *end, *token;
    510 
    511 	while ((token = strsep(&option, ", \t")) != NULL) {
    512 		if (*token == '\0')
    513 			continue;
    514 		if ((token[0] != '1' && token[0] != '2') || token[1] != '.')
    515 			errx(1, "malformed -o option field");
    516 		fieldno = strtol(token + 2, &end, 10);
    517 		if (*end)
    518 			errx(1, "malformed -o option field");
    519 		if (fieldno == 0)
    520 			errx(1, "field numbers are 1 based");
    521 		if (olistcnt == olistalloc) {
    522 			olistalloc += 50;
    523 			if ((olist = realloc(olist,
    524 			    olistalloc * sizeof(OLIST))) == NULL)
    525 				enomem();
    526 		}
    527 		olist[olistcnt].fileno = token[0] - '0';
    528 		olist[olistcnt].fieldno = fieldno - 1;
    529 		++olistcnt;
    530 	}
    531 }
    532 
    533 void
    534 obsolete(argv)
    535 	char **argv;
    536 {
    537 	int len;
    538 	char **p, *ap, *t;
    539 
    540 	while ((ap = *++argv) != NULL) {
    541 		/* Return if "--". */
    542 		if (ap[0] == '-' && ap[1] == '-')
    543 			return;
    544 		switch (ap[1]) {
    545 		case 'a':
    546 			/*
    547 			 * The original join allowed "-a", which meant the
    548 			 * same as -a1 plus -a2.  POSIX 1003.2, Draft 11.2
    549 			 * only specifies this as "-a 1" and "a -2", so we
    550 			 * have to use another option flag, one that is
    551 			 * unlikely to ever be used or accidentally entered
    552 			 * on the command line.  (Well, we could reallocate
    553 			 * the argv array, but that hardly seems worthwhile.)
    554 			 */
    555 			if (ap[2] == '\0')
    556 				ap[1] = '\01';
    557 			break;
    558 		case 'j':
    559 			/*
    560 			 * The original join allowed "-j[12] arg" and "-j arg".
    561 			 * Convert the former to "-[12] arg".  Don't convert
    562 			 * the latter since getopt(3) can handle it.
    563 			 */
    564 			switch(ap[2]) {
    565 			case '1':
    566 				if (ap[3] != '\0')
    567 					goto jbad;
    568 				ap[1] = '1';
    569 				ap[2] = '\0';
    570 				break;
    571 			case '2':
    572 				if (ap[3] != '\0')
    573 					goto jbad;
    574 				ap[1] = '2';
    575 				ap[2] = '\0';
    576 				break;
    577 			case '\0':
    578 				break;
    579 			default:
    580 jbad:				errx(1, "illegal option -- %s", ap);
    581 				usage();
    582 			}
    583 			break;
    584 		case 'o':
    585 			/*
    586 			 * The original join allowed "-o arg arg".  Convert to
    587 			 * "-o arg -o arg".
    588 			 */
    589 			if (ap[2] != '\0')
    590 				break;
    591 			for (p = argv + 2; *p; ++p) {
    592 				if ((p[0][0] != '1' && p[0][0] != '2') ||
    593 				    p[0][1] != '.')
    594 					break;
    595 				len = strlen(*p);
    596 				if (len - 2 != strspn(*p + 2, "0123456789"))
    597 					break;
    598 				if ((t = malloc(len + 3)) == NULL)
    599 					enomem();
    600 				t[0] = '-';
    601 				t[1] = 'o';
    602 				memmove(t + 2, *p, len + 1);
    603 				*p = t;
    604 			}
    605 			argv = p - 1;
    606 			break;
    607 		}
    608 	}
    609 }
    610 
    611 void
    612 enomem()
    613 {
    614 	errx(1, "no memory");
    615 }
    616 
    617 void
    618 usage()
    619 {
    620 	(void)fprintf(stderr, "%s%s\n",
    621 	    "usage: join [-a fileno | -v fileno ] [-e string] [-1 field] ",
    622 	    "[-2 field]\n            [-o list] [-t char] file1 file2");
    623 	exit(1);
    624 }
    625