Home | History | Annotate | Line # | Download | only in join
join.c revision 1.13
      1 /*	$NetBSD: join.c,v 1.13 1998/08/25 20:59:38 ross 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.13 1998/08/25 20:59:38 ross 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 <string.h>
     62 #include <unistd.h>
     63 
     64 /*
     65  * There's a structure per input file which encapsulates the state of the
     66  * file.  We repeatedly read lines from each file until we've read in all
     67  * the consecutive lines from the file with a common join field.  Then we
     68  * compare the set of lines with an equivalent set from the other file.
     69  */
     70 typedef struct {
     71 	char *line;		/* line */
     72 	u_long linealloc;	/* line allocated count */
     73 	char **fields;		/* line field(s) */
     74 	u_long fieldcnt;	/* line field(s) count */
     75 	u_long fieldalloc;	/* line field(s) allocated count */
     76 } LINE;
     77 
     78 typedef struct {
     79 	FILE *fp;		/* file descriptor */
     80 	u_long joinf;		/* join field (-1, -2, -j) */
     81 	int unpair;		/* output unpairable lines (-a) */
     82 	int number;		/* 1 for file 1, 2 for file 2 */
     83 
     84 	LINE *set;		/* set of lines with same field */
     85 	u_long pushback;	/* line on the stack */
     86 	u_long setcnt;		/* set count */
     87 	u_long setalloc;	/* set allocated count */
     88 } INPUT;
     89 INPUT input1 = { NULL, 0, 0, 1, NULL, -1, 0, 0, },
     90       input2 = { NULL, 0, 0, 1, NULL, -1, 0, 0, };
     91 
     92 typedef struct {
     93 	u_long	fileno;		/* file number */
     94 	u_long	fieldno;	/* field number */
     95 } OLIST;
     96 OLIST *olist;			/* output field list */
     97 u_long olistcnt;		/* output field list count */
     98 u_long olistalloc;		/* output field allocated count */
     99 
    100 int joinout = 1;		/* show lines with matched join fields (-v) */
    101 int needsep;			/* need separator character */
    102 int spans = 1;			/* span multiple delimiters (-t) */
    103 char *empty;			/* empty field replacement string (-e) */
    104 char *tabchar = " \t";		/* delimiter characters (-t) */
    105 
    106 int  cmp __P((LINE *, u_long, LINE *, u_long));
    107 void enomem __P((void));
    108 void fieldarg __P((char *));
    109 void joinlines __P((INPUT *, INPUT *));
    110 int  main __P((int, char **));
    111 void obsolete __P((char **));
    112 void outfield __P((LINE *, u_long));
    113 void outoneline __P((INPUT *, LINE *));
    114 void outtwoline __P((INPUT *, LINE *, INPUT *, LINE *));
    115 void slurp __P((INPUT *));
    116 void usage __P((void));
    117 
    118 int
    119 main(argc, argv)
    120 	int argc;
    121 	char *argv[];
    122 {
    123 	INPUT *F1, *F2;
    124 	int aflag, ch, cval, vflag;
    125 	char *end;
    126 
    127 	F1 = &input1;
    128 	F2 = &input2;
    129 
    130 	aflag = vflag = 0;
    131 	obsolete(argv);
    132 	while ((ch = getopt(argc, argv, "\01a:e:j:1:2:o:t:v:")) != -1) {
    133 		switch (ch) {
    134 		case '\01':
    135 			aflag = 1;
    136 			F1->unpair = F2->unpair = 1;
    137 			break;
    138 		case '1':
    139 			if ((F1->joinf = strtol(optarg, &end, 10)) < 1) {
    140 				warnx("-1 option field number less than 1");
    141 				usage();
    142 			}
    143 			if (*end) {
    144 				warnx("illegal field number -- %s", optarg);
    145 				usage();
    146 			}
    147 			--F1->joinf;
    148 			break;
    149 		case '2':
    150 			if ((F2->joinf = strtol(optarg, &end, 10)) < 1) {
    151 				warnx("-2 option field number less than 1");
    152 				usage();
    153 			}
    154 			if (*end) {
    155 				warnx("illegal field number -- %s", optarg);
    156 				usage();
    157 			}
    158 			--F2->joinf;
    159 			break;
    160 		case 'a':
    161 			aflag = 1;
    162 			switch(strtol(optarg, &end, 10)) {
    163 			case 1:
    164 				F1->unpair = 1;
    165 				break;
    166 			case 2:
    167 				F2->unpair = 1;
    168 				break;
    169 			default:
    170 				warnx("-a option file number not 1 or 2");
    171 				usage();
    172 				break;
    173 			}
    174 			if (*end) {
    175 				warnx("illegal file number -- %s", optarg);
    176 				usage();
    177 			}
    178 			break;
    179 		case 'e':
    180 			empty = optarg;
    181 			break;
    182 		case 'j':
    183 			if ((F1->joinf = F2->joinf =
    184 			    strtol(optarg, &end, 10)) < 1) {
    185 				warnx("-j option field number less than 1");
    186 				usage();
    187 			}
    188 			if (*end) {
    189 				warnx("illegal field number -- %s", optarg);
    190 				usage();
    191 			}
    192 			--F1->joinf;
    193 			--F2->joinf;
    194 			break;
    195 		case 'o':
    196 			fieldarg(optarg);
    197 			break;
    198 		case 't':
    199 			spans = 0;
    200 			if (strlen(tabchar = optarg) != 1) {
    201 				warnx("illegal tab character specification");
    202 				usage();
    203 			}
    204 			break;
    205 		case 'v':
    206 			vflag = 1;
    207 			joinout = 0;
    208 			switch(strtol(optarg, &end, 10)) {
    209 			case 1:
    210 				F1->unpair = 1;
    211 				break;
    212 			case 2:
    213 				F2->unpair = 1;
    214 				break;
    215 			default:
    216 				warnx("-v option file number not 1 or 2");
    217 				usage();
    218 				break;
    219 			}
    220 			if (*end) {
    221 				warnx("illegal file number -- %s", optarg);
    222 				usage();
    223 			}
    224 			break;
    225 		case '?':
    226 		default:
    227 			usage();
    228 		}
    229 	}
    230 	argc -= optind;
    231 	argv += optind;
    232 
    233 	if (aflag && vflag)
    234 		errx(1, "-a and -v options mutually exclusive");
    235 
    236 	if (argc != 2)
    237 		usage();
    238 
    239 	/* Open the files; "-" means stdin. */
    240 	if (!strcmp(*argv, "-"))
    241 		F1->fp = stdin;
    242 	else if ((F1->fp = fopen(*argv, "r")) == NULL)
    243 		err(1, "%s", *argv);
    244 	++argv;
    245 	if (!strcmp(*argv, "-"))
    246 		F2->fp = stdin;
    247 	else if ((F2->fp = fopen(*argv, "r")) == NULL)
    248 		err(1, "%s", *argv);
    249 	if (F1->fp == stdin && F2->fp == stdin)
    250 		errx(1, "only one input file may be stdin");
    251 
    252 	slurp(F1);
    253 	slurp(F2);
    254 	while (F1->setcnt && F2->setcnt) {
    255 		cval = cmp(F1->set, F1->joinf, F2->set, F2->joinf);
    256 		if (cval == 0) {
    257 			/* Oh joy, oh rapture, oh beauty divine! */
    258 			if (joinout)
    259 				joinlines(F1, F2);
    260 			slurp(F1);
    261 			slurp(F2);
    262 		} else if (cval < 0) {
    263 			/* File 1 takes the lead... */
    264 			if (F1->unpair)
    265 				joinlines(F1, NULL);
    266 			slurp(F1);
    267 		} else {
    268 			/* File 2 takes the lead... */
    269 			if (F2->unpair)
    270 				joinlines(F2, NULL);
    271 			slurp(F2);
    272 		}
    273 	}
    274 
    275 	/*
    276 	 * Now that one of the files is used up, optionally output any
    277 	 * remaining lines from the other file.
    278 	 */
    279 	if (F1->unpair)
    280 		while (F1->setcnt) {
    281 			joinlines(F1, NULL);
    282 			slurp(F1);
    283 		}
    284 	if (F2->unpair)
    285 		while (F2->setcnt) {
    286 			joinlines(F2, NULL);
    287 			slurp(F2);
    288 		}
    289 	exit(0);
    290 }
    291 
    292 void
    293 slurp(F)
    294 	INPUT *F;
    295 {
    296 	LINE *lp, *lastlp;
    297 	LINE tmp;
    298 	size_t len;
    299 	int cnt;
    300 	char *bp, *fieldp;
    301 
    302 	/*
    303 	 * Read all of the lines from an input file that have the same
    304 	 * join field.
    305 	 */
    306 	F->setcnt = 0;
    307 	for (lastlp = NULL;; ++F->setcnt, lastlp = lp) {
    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 			F->setalloc += 100;
    316 			if ((F->set = realloc(F->set,
    317 			    F->setalloc * sizeof(LINE))) == NULL)
    318 				enomem();
    319 			memset(F->set + cnt, 0, 100 * sizeof(LINE *));
    320 		}
    321 
    322 		/*
    323 		 * Get any pushed back line, else get the next line.  Allocate
    324 		 * space as necessary.  If taking the line from the stack swap
    325 		 * the two structures so that we don't lose the allocated space.
    326 		 * This could be avoided by doing another level of indirection,
    327 		 * but it's probably okay as is.
    328 		 */
    329 		lp = &F->set[F->setcnt];
    330 		if (F->pushback != -1) {
    331 			tmp = F->set[F->setcnt];
    332 			F->set[F->setcnt] = F->set[F->pushback];
    333 			F->set[F->pushback] = tmp;
    334 			F->pushback = -1;
    335 			continue;
    336 		}
    337 		if ((bp = fgetln(F->fp, &len)) == NULL)
    338 			return;
    339 		if (lp->linealloc <= len + 1) {
    340 			if (lp->linealloc == 0)
    341 				lp->linealloc = 128;
    342 			while (lp->linealloc <= len + 1)
    343 				lp->linealloc *= 2;
    344 
    345 			if ((lp->line = realloc(lp->line,
    346 			    lp->linealloc * sizeof(char))) == NULL)
    347 				enomem();
    348 		}
    349 		memmove(lp->line, bp, len+1);
    350 
    351 		/* Replace trailing newline, if it exists. */
    352 		if (bp[len - 1] == '\n')
    353 			lp->line[len - 1] = '\0';
    354 		else
    355 			lp->line[len] = '\0';
    356 		bp = lp->line;
    357 
    358 		/* Split the line into fields, allocate space as necessary. */
    359 		lp->fieldcnt = 0;
    360 		while ((fieldp = strsep(&bp, tabchar)) != NULL) {
    361 			if (spans && *fieldp == '\0')
    362 				continue;
    363 			if (lp->fieldcnt == lp->fieldalloc) {
    364 				lp->fieldalloc += 100;
    365 				if ((lp->fields = realloc(lp->fields,
    366 				    lp->fieldalloc * sizeof(char *))) == NULL)
    367 					enomem();
    368 			}
    369 			lp->fields[lp->fieldcnt++] = fieldp;
    370 		}
    371 
    372 		/* See if the join field value has changed. */
    373 		if (lastlp != NULL && cmp(lp, F->joinf, lastlp, F->joinf)) {
    374 			F->pushback = F->setcnt;
    375 			break;
    376 		}
    377 	}
    378 }
    379 
    380 int
    381 cmp(lp1, fieldno1, lp2, fieldno2)
    382 	LINE *lp1, *lp2;
    383 	u_long fieldno1, fieldno2;
    384 {
    385 
    386 	if (lp1->fieldcnt <= fieldno1)
    387 		return (lp2->fieldcnt < fieldno2 ? 0 : 1);
    388 	if (lp2->fieldcnt <= fieldno2)
    389 		return (-1);
    390 	return (strcmp(lp1->fields[fieldno1], lp2->fields[fieldno2]));
    391 }
    392 
    393 void
    394 joinlines(F1, F2)
    395 	INPUT *F1, *F2;
    396 {
    397 	int cnt1, cnt2;
    398 
    399 	/*
    400 	 * Output the results of a join comparison.  The output may be from
    401 	 * either file 1 or file 2 (in which case the first argument is the
    402 	 * file from which to output) or from both.
    403 	 */
    404 	if (F2 == NULL) {
    405 		for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
    406 			outoneline(F1, &F1->set[cnt1]);
    407 		return;
    408 	}
    409 	for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
    410 		for (cnt2 = 0; cnt2 < F2->setcnt; ++cnt2)
    411 			outtwoline(F1, &F1->set[cnt1], F2, &F2->set[cnt2]);
    412 }
    413 
    414 void
    415 outoneline(F, lp)
    416 	INPUT *F;
    417 	LINE *lp;
    418 {
    419 	int cnt;
    420 
    421 	/*
    422 	 * Output a single line from one of the files, according to the
    423 	 * join rules.  This happens when we are writing unmatched single
    424 	 * lines.  Output empty fields in the right places.
    425 	 */
    426 	if (olist)
    427 		for (cnt = 0; cnt < olistcnt; ++cnt) {
    428 			if (olist[cnt].fileno == F->number)
    429 				outfield(lp, olist[cnt].fieldno);
    430 		}
    431 	else
    432 		for (cnt = 0; cnt < lp->fieldcnt; ++cnt)
    433 			outfield(lp, cnt);
    434 	(void)printf("\n");
    435 	if (ferror(stdout))
    436 		err(1, "stdout");
    437 	needsep = 0;
    438 }
    439 
    440 void
    441 outtwoline(F1, lp1, F2, lp2)
    442 	INPUT *F1, *F2;
    443 	LINE *lp1, *lp2;
    444 {
    445 	int cnt;
    446 
    447 	/* Output a pair of lines according to the join list (if any). */
    448 	if (olist)
    449 		for (cnt = 0; cnt < olistcnt; ++cnt)
    450 			if (olist[cnt].fileno == 1)
    451 				outfield(lp1, olist[cnt].fieldno);
    452 			else /* if (olist[cnt].fileno == 2) */
    453 				outfield(lp2, olist[cnt].fieldno);
    454 	else {
    455 		/*
    456 		 * Output the join field, then the remaining fields from F1
    457 		 * and F2.
    458 		 */
    459 		outfield(lp1, F1->joinf);
    460 		for (cnt = 0; cnt < lp1->fieldcnt; ++cnt)
    461 			if (F1->joinf != cnt)
    462 				outfield(lp1, cnt);
    463 		for (cnt = 0; cnt < lp2->fieldcnt; ++cnt)
    464 			if (F2->joinf != cnt)
    465 				outfield(lp2, cnt);
    466 	}
    467 	(void)printf("\n");
    468 	if (ferror(stdout))
    469 		err(1, "stdout");
    470 	needsep = 0;
    471 }
    472 
    473 void
    474 outfield(lp, fieldno)
    475 	LINE *lp;
    476 	u_long fieldno;
    477 {
    478 	if (needsep++)
    479 		(void)printf("%c", *tabchar);
    480 	if (!ferror(stdout)) {
    481 		if (lp->fieldcnt < fieldno) {
    482 			if (empty != NULL)
    483 				(void)printf("%s", empty);
    484 		} else {
    485 			if (*lp->fields[fieldno] == '\0')
    486 				return;
    487 			(void)printf("%s", lp->fields[fieldno]);
    488 		}
    489 	}
    490 	if (ferror(stdout))
    491 		err(1, "stdout");
    492 }
    493 
    494 /*
    495  * Convert an output list argument "2.1, 1.3, 2.4" into an array of output
    496  * fields.
    497  */
    498 void
    499 fieldarg(option)
    500 	char *option;
    501 {
    502 	u_long fieldno;
    503 	char *end, *token;
    504 
    505 	while ((token = strsep(&option, " \t")) != NULL) {
    506 		if (*token == '\0')
    507 			continue;
    508 		if ((token[0] != '1' && token[0] != '2') || token[1] != '.')
    509 			errx(1, "malformed -o option field");
    510 		fieldno = strtol(token + 2, &end, 10);
    511 		if (*end)
    512 			errx(1, "malformed -o option field");
    513 		if (fieldno == 0)
    514 			errx(1, "field numbers are 1 based");
    515 		if (olistcnt == olistalloc) {
    516 			olistalloc += 50;
    517 			if ((olist = realloc(olist,
    518 			    olistalloc * sizeof(OLIST))) == NULL)
    519 				enomem();
    520 		}
    521 		olist[olistcnt].fileno = token[0] - '0';
    522 		olist[olistcnt].fieldno = fieldno - 1;
    523 		++olistcnt;
    524 	}
    525 }
    526 
    527 void
    528 obsolete(argv)
    529 	char **argv;
    530 {
    531 	int len;
    532 	char **p, *ap, *t;
    533 
    534 	while ((ap = *++argv) != NULL) {
    535 		/* Return if "--". */
    536 		if (ap[0] == '-' && ap[1] == '-')
    537 			return;
    538 		switch (ap[1]) {
    539 		case 'a':
    540 			/*
    541 			 * The original join allowed "-a", which meant the
    542 			 * same as -a1 plus -a2.  POSIX 1003.2, Draft 11.2
    543 			 * only specifies this as "-a 1" and "a -2", so we
    544 			 * have to use another option flag, one that is
    545 			 * unlikely to ever be used or accidentally entered
    546 			 * on the command line.  (Well, we could reallocate
    547 			 * the argv array, but that hardly seems worthwhile.)
    548 			 */
    549 			if (ap[2] == '\0')
    550 				ap[1] = '\01';
    551 			break;
    552 		case 'j':
    553 			/*
    554 			 * The original join allowed "-j[12] arg" and "-j arg".
    555 			 * Convert the former to "-[12] arg".  Don't convert
    556 			 * the latter since getopt(3) can handle it.
    557 			 */
    558 			switch(ap[2]) {
    559 			case '1':
    560 				if (ap[3] != '\0')
    561 					goto jbad;
    562 				ap[1] = '1';
    563 				ap[2] = '\0';
    564 				break;
    565 			case '2':
    566 				if (ap[3] != '\0')
    567 					goto jbad;
    568 				ap[1] = '2';
    569 				ap[2] = '\0';
    570 				break;
    571 			case '\0':
    572 				break;
    573 			default:
    574 jbad:				errx(1, "illegal option -- %s", ap);
    575 				usage();
    576 			}
    577 			break;
    578 		case 'o':
    579 			/*
    580 			 * The original join allowed "-o arg arg".  Convert to
    581 			 * "-o arg -o arg".
    582 			 */
    583 			if (ap[2] != '\0')
    584 				break;
    585 			for (p = argv + 2; *p; ++p) {
    586 				if ((p[0][0] != '1' && p[0][0] != '2') ||
    587 				    p[0][1] != '.')
    588 					break;
    589 				len = strlen(*p);
    590 				if (len - 2 != strspn(*p + 2, "0123456789"))
    591 					break;
    592 				if ((t = malloc(len + 3)) == NULL)
    593 					enomem();
    594 				t[0] = '-';
    595 				t[1] = 'o';
    596 				memmove(t + 2, *p, len + 1);
    597 				*p = t;
    598 			}
    599 			argv = p - 1;
    600 			break;
    601 		}
    602 	}
    603 }
    604 
    605 void
    606 enomem()
    607 {
    608 	errx(1, "no memory");
    609 }
    610 
    611 void
    612 usage()
    613 {
    614 	(void)fprintf(stderr, "%s%s\n",
    615 	    "usage: join [-a fileno | -v fileno ] [-e string] [-1 field] ",
    616 	    "[-2 field]\n            [-o list] [-t char] file1 file2");
    617 	exit(1);
    618 }
    619