Home | History | Annotate | Line # | Download | only in join
join.c revision 1.16
      1 /*	$NetBSD: join.c,v 1.16 1999/08/10 20:09:02 tron 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.16 1999/08/10 20:09:02 tron 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, *lastlp;
    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 	F->setcnt = 0;
    308 	for (lastlp = NULL;; ++F->setcnt, lastlp = lp) {
    309 		/*
    310 		 * If we're out of space to hold line structures, allocate
    311 		 * more.  Initialize the structure so that we know that this
    312 		 * is new space.
    313 		 */
    314 		if (F->setcnt == F->setalloc) {
    315 			cnt = F->setalloc;
    316 			F->setalloc += 100;
    317 			if ((F->set = realloc(F->set,
    318 			    F->setalloc * sizeof(LINE))) == NULL)
    319 				enomem();
    320 			memset(F->set + cnt, 0, 100 * sizeof(LINE));
    321 		}
    322 
    323 		/*
    324 		 * Get any pushed back line, else get the next line.  Allocate
    325 		 * space as necessary.  If taking the line from the stack swap
    326 		 * the two structures so that we don't lose the allocated space.
    327 		 * This could be avoided by doing another level of indirection,
    328 		 * but it's probably okay as is.
    329 		 */
    330 		lp = &F->set[F->setcnt];
    331 		if (F->pushback != -1) {
    332 			tmp = F->set[F->setcnt];
    333 			F->set[F->setcnt] = F->set[F->pushback];
    334 			F->set[F->pushback] = tmp;
    335 			F->pushback = -1;
    336 			continue;
    337 		}
    338 		if ((bp = fgetln(F->fp, &len)) == NULL)
    339 			return;
    340 		if (lp->linealloc <= len + 1) {
    341 			if (lp->linealloc == 0)
    342 				lp->linealloc = 128;
    343 			while (lp->linealloc <= len + 1)
    344 				lp->linealloc *= 2;
    345 
    346 			if ((lp->line = realloc(lp->line,
    347 			    lp->linealloc * sizeof(char))) == NULL)
    348 				enomem();
    349 		}
    350 		memmove(lp->line, bp, len);
    351 
    352 		/* Replace trailing newline, if it exists. */
    353 		if (bp[len - 1] == '\n')
    354 			lp->line[len - 1] = '\0';
    355 		else
    356 			lp->line[len] = '\0';
    357 		bp = lp->line;
    358 
    359 		/* Split the line into fields, allocate space as necessary. */
    360 		lp->fieldcnt = 0;
    361 		while ((fieldp = strsep(&bp, tabchar)) != NULL) {
    362 			if (spans && *fieldp == '\0')
    363 				continue;
    364 			if (lp->fieldcnt == lp->fieldalloc) {
    365 				lp->fieldalloc += 100;
    366 				if ((lp->fields = realloc(lp->fields,
    367 				    lp->fieldalloc * sizeof(char *))) == NULL)
    368 					enomem();
    369 			}
    370 			lp->fields[lp->fieldcnt++] = fieldp;
    371 		}
    372 
    373 		/* See if the join field value has changed. */
    374 		if (lastlp != NULL && cmp(lp, F->joinf, lastlp, F->joinf)) {
    375 			F->pushback = F->setcnt;
    376 			break;
    377 		}
    378 	}
    379 }
    380 
    381 int
    382 cmp(lp1, fieldno1, lp2, fieldno2)
    383 	LINE *lp1, *lp2;
    384 	u_long fieldno1, fieldno2;
    385 {
    386 
    387 	if (lp1->fieldcnt <= fieldno1)
    388 		return (lp2->fieldcnt < fieldno2 ? 0 : 1);
    389 	if (lp2->fieldcnt <= fieldno2)
    390 		return (-1);
    391 	return (strcmp(lp1->fields[fieldno1], lp2->fields[fieldno2]));
    392 }
    393 
    394 void
    395 joinlines(F1, F2)
    396 	INPUT *F1, *F2;
    397 {
    398 	int cnt1, cnt2;
    399 
    400 	/*
    401 	 * Output the results of a join comparison.  The output may be from
    402 	 * either file 1 or file 2 (in which case the first argument is the
    403 	 * file from which to output) or from both.
    404 	 */
    405 	if (F2 == NULL) {
    406 		for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
    407 			outoneline(F1, &F1->set[cnt1]);
    408 		return;
    409 	}
    410 	for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
    411 		for (cnt2 = 0; cnt2 < F2->setcnt; ++cnt2)
    412 			outtwoline(F1, &F1->set[cnt1], F2, &F2->set[cnt2]);
    413 }
    414 
    415 void
    416 outoneline(F, lp)
    417 	INPUT *F;
    418 	LINE *lp;
    419 {
    420 	int cnt;
    421 
    422 	/*
    423 	 * Output a single line from one of the files, according to the
    424 	 * join rules.  This happens when we are writing unmatched single
    425 	 * lines.  Output empty fields in the right places.
    426 	 */
    427 	if (olist)
    428 		for (cnt = 0; cnt < olistcnt; ++cnt) {
    429 			if (olist[cnt].fileno == F->number)
    430 				outfield(lp, olist[cnt].fieldno);
    431 		}
    432 	else
    433 		for (cnt = 0; cnt < lp->fieldcnt; ++cnt)
    434 			outfield(lp, cnt);
    435 	(void)printf("\n");
    436 	if (ferror(stdout))
    437 		err(1, "stdout");
    438 	needsep = 0;
    439 }
    440 
    441 void
    442 outtwoline(F1, lp1, F2, lp2)
    443 	INPUT *F1, *F2;
    444 	LINE *lp1, *lp2;
    445 {
    446 	int cnt;
    447 
    448 	/* Output a pair of lines according to the join list (if any). */
    449 	if (olist) {
    450 		for (cnt = 0; cnt < olistcnt; ++cnt)
    451 			if (olist[cnt].fileno == 1)
    452 				outfield(lp1, olist[cnt].fieldno);
    453 			else /* if (olist[cnt].fileno == 2) */
    454 				outfield(lp2, olist[cnt].fieldno);
    455 	} else {
    456 		/*
    457 		 * Output the join field, then the remaining fields from F1
    458 		 * and F2.
    459 		 */
    460 		outfield(lp1, F1->joinf);
    461 		for (cnt = 0; cnt < lp1->fieldcnt; ++cnt)
    462 			if (F1->joinf != cnt)
    463 				outfield(lp1, cnt);
    464 		for (cnt = 0; cnt < lp2->fieldcnt; ++cnt)
    465 			if (F2->joinf != cnt)
    466 				outfield(lp2, cnt);
    467 	}
    468 	(void)printf("\n");
    469 	if (ferror(stdout))
    470 		err(1, "stdout");
    471 	needsep = 0;
    472 }
    473 
    474 void
    475 outfield(lp, fieldno)
    476 	LINE *lp;
    477 	u_long fieldno;
    478 {
    479 	if (needsep++)
    480 		(void)printf("%c", *tabchar);
    481 	if (!ferror(stdout)) {
    482 		if (lp->fieldcnt < fieldno) {
    483 			if (empty != NULL)
    484 				(void)printf("%s", empty);
    485 		} else {
    486 			if (*lp->fields[fieldno] == '\0')
    487 				return;
    488 			(void)printf("%s", lp->fields[fieldno]);
    489 		}
    490 	}
    491 	if (ferror(stdout))
    492 		err(1, "stdout");
    493 }
    494 
    495 /*
    496  * Convert an output list argument "2.1, 1.3, 2.4" into an array of output
    497  * fields.
    498  */
    499 void
    500 fieldarg(option)
    501 	char *option;
    502 {
    503 	u_long fieldno;
    504 	char *end, *token;
    505 
    506 	while ((token = strsep(&option, " \t")) != NULL) {
    507 		if (*token == '\0')
    508 			continue;
    509 		if ((token[0] != '1' && token[0] != '2') || token[1] != '.')
    510 			errx(1, "malformed -o option field");
    511 		fieldno = strtol(token + 2, &end, 10);
    512 		if (*end)
    513 			errx(1, "malformed -o option field");
    514 		if (fieldno == 0)
    515 			errx(1, "field numbers are 1 based");
    516 		if (olistcnt == olistalloc) {
    517 			olistalloc += 50;
    518 			if ((olist = realloc(olist,
    519 			    olistalloc * sizeof(OLIST))) == NULL)
    520 				enomem();
    521 		}
    522 		olist[olistcnt].fileno = token[0] - '0';
    523 		olist[olistcnt].fieldno = fieldno - 1;
    524 		++olistcnt;
    525 	}
    526 }
    527 
    528 void
    529 obsolete(argv)
    530 	char **argv;
    531 {
    532 	int len;
    533 	char **p, *ap, *t;
    534 
    535 	while ((ap = *++argv) != NULL) {
    536 		/* Return if "--". */
    537 		if (ap[0] == '-' && ap[1] == '-')
    538 			return;
    539 		switch (ap[1]) {
    540 		case 'a':
    541 			/*
    542 			 * The original join allowed "-a", which meant the
    543 			 * same as -a1 plus -a2.  POSIX 1003.2, Draft 11.2
    544 			 * only specifies this as "-a 1" and "a -2", so we
    545 			 * have to use another option flag, one that is
    546 			 * unlikely to ever be used or accidentally entered
    547 			 * on the command line.  (Well, we could reallocate
    548 			 * the argv array, but that hardly seems worthwhile.)
    549 			 */
    550 			if (ap[2] == '\0')
    551 				ap[1] = '\01';
    552 			break;
    553 		case 'j':
    554 			/*
    555 			 * The original join allowed "-j[12] arg" and "-j arg".
    556 			 * Convert the former to "-[12] arg".  Don't convert
    557 			 * the latter since getopt(3) can handle it.
    558 			 */
    559 			switch(ap[2]) {
    560 			case '1':
    561 				if (ap[3] != '\0')
    562 					goto jbad;
    563 				ap[1] = '1';
    564 				ap[2] = '\0';
    565 				break;
    566 			case '2':
    567 				if (ap[3] != '\0')
    568 					goto jbad;
    569 				ap[1] = '2';
    570 				ap[2] = '\0';
    571 				break;
    572 			case '\0':
    573 				break;
    574 			default:
    575 jbad:				errx(1, "illegal option -- %s", ap);
    576 				usage();
    577 			}
    578 			break;
    579 		case 'o':
    580 			/*
    581 			 * The original join allowed "-o arg arg".  Convert to
    582 			 * "-o arg -o arg".
    583 			 */
    584 			if (ap[2] != '\0')
    585 				break;
    586 			for (p = argv + 2; *p; ++p) {
    587 				if ((p[0][0] != '1' && p[0][0] != '2') ||
    588 				    p[0][1] != '.')
    589 					break;
    590 				len = strlen(*p);
    591 				if (len - 2 != strspn(*p + 2, "0123456789"))
    592 					break;
    593 				if ((t = malloc(len + 3)) == NULL)
    594 					enomem();
    595 				t[0] = '-';
    596 				t[1] = 'o';
    597 				memmove(t + 2, *p, len + 1);
    598 				*p = t;
    599 			}
    600 			argv = p - 1;
    601 			break;
    602 		}
    603 	}
    604 }
    605 
    606 void
    607 enomem()
    608 {
    609 	errx(1, "no memory");
    610 }
    611 
    612 void
    613 usage()
    614 {
    615 	(void)fprintf(stderr, "%s%s\n",
    616 	    "usage: join [-a fileno | -v fileno ] [-e string] [-1 field] ",
    617 	    "[-2 field]\n            [-o list] [-t char] file1 file2");
    618 	exit(1);
    619 }
    620