1 /* 2 * Copyright (c) 1989 The Regents of the University of California. 3 * All rights reserved. 4 * 5 * This code is derived from software contributed to Berkeley by 6 * Case Larsen. 7 * 8 * %sccs.include.redist.c% 9 */ 10 11 #ifndef lint 12 char copyright[] = 13 "@(#) Copyright (c) 1989 The Regents of the University of California.\n\ 14 All rights reserved.\n"; 15 #endif /* not lint */ 16 17 #ifndef lint 18 static char sccsid[] = "@(#)comm.c 5.4 (Berkeley) 06/01/90"; 19 #endif /* not lint */ 20 21 #include <sys/file.h> 22 #include <limits.h> 23 #include <stdio.h> 24 25 #define MAXLINELEN (LINE_MAX + 1) 26 27 char *tabs[] = { "", "\t", "\t\t" }; 28 29 main(argc,argv) 30 int argc; 31 char *argv[]; 32 { 33 register int comp, file1done, file2done, read1, read2; 34 register char *col1, *col2, *col3; 35 int ch, flag1, flag2, flag3; 36 FILE *fp1, *fp2, *file(); 37 char **p, line1[MAXLINELEN], line2[MAXLINELEN]; 38 extern int optind; 39 40 flag1 = flag2 = flag3 = 1; 41 while ((ch = getopt(argc, argv, "-123")) != EOF) 42 switch(ch) { 43 case '-': 44 --optind; 45 goto done; 46 case '1': 47 flag1 = 0; 48 break; 49 case '2': 50 flag2 = 0; 51 break; 52 case '3': 53 flag3 = 0; 54 break; 55 case '?': 56 default: 57 usage(); 58 } 59 done: argc -= optind; 60 argv += optind; 61 62 if (argc != 2) 63 usage(); 64 65 fp1 = file(argv[0]); 66 fp2 = file(argv[1]); 67 68 /* for each column printed, add another tab offset */ 69 p = tabs; 70 if (flag1) 71 col1 = *p++; 72 if (flag2) 73 col2 = *p++; 74 if (flag3) 75 col3 = *p++; 76 77 for (read1 = read2 = 1;;) { 78 /* read next line, check for EOF */ 79 if (read1) 80 file1done = !fgets(line1, MAXLINELEN, fp1); 81 if (read2) 82 file2done = !fgets(line2, MAXLINELEN, fp2); 83 84 /* if one file done, display the rest of the other file */ 85 if (file1done) { 86 if (!file2done && col2) 87 show(fp2, col2, line2); 88 break; 89 } 90 if (file2done) { 91 if (!file1done && col1) 92 show(fp1, col1, line1); 93 break; 94 } 95 96 /* lines are the same */ 97 if (!(comp = strcmp(line1, line2))) { 98 read1 = read2 = 1; 99 if (col3) 100 (void)printf("%s%s", col3, line1); 101 continue; 102 } 103 104 /* lines are different */ 105 if (comp < 0) { 106 read1 = 1; 107 read2 = 0; 108 if (col1) 109 (void)printf("%s%s", col1, line1); 110 } else { 111 read1 = 0; 112 read2 = 1; 113 if (col2) 114 (void)printf("%s%s", col2, line2); 115 } 116 } 117 exit(0); 118 } 119 120 show(fp, offset, buf) 121 FILE *fp; 122 char *offset, *buf; 123 { 124 do { 125 (void)printf("%s%s", offset, buf); 126 } while (fgets(buf, MAXLINELEN, fp)); 127 } 128 129 FILE * 130 file(name) 131 char *name; 132 { 133 FILE *fp; 134 135 if (!strcmp(name, "-")) 136 return(stdin); 137 if (!(fp = fopen(name, "r"))) { 138 (void)fprintf(stderr, "comm: can't read %s.\n", name); 139 exit(1); 140 } 141 return(fp); 142 } 143 144 usage() 145 { 146 (void)fprintf(stderr, "usage: comm [-123] [ - ] file1 file2\n"); 147 exit(1); 148 } 149