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