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