cmp.c (2098B)
1 #include <u.h> 2 #include <libc.h> 3 4 #define BUF 65536 5 6 int sflag = 0; 7 int lflag = 0; 8 int Lflag = 0; 9 10 static void usage(void); 11 12 void 13 main(int argc, char *argv[]) 14 { 15 int n, i; 16 uchar *p, *q; 17 uchar buf1[BUF], buf2[BUF]; 18 int f1, f2; 19 vlong nc = 1, o, l = 1; 20 char *name1, *name2; 21 uchar *b1s, *b1e, *b2s, *b2e; 22 23 ARGBEGIN{ 24 case 's': sflag = 1; break; 25 case 'l': lflag = 1; break; 26 case 'L': Lflag = 1; break; 27 default: usage(); 28 }ARGEND 29 if(argc < 2) 30 usage(); 31 if((f1 = open(name1 = *argv++, OREAD)) == -1){ 32 if(!sflag) perror(name1); 33 exits("open"); 34 } 35 if((f2 = open(name2 = *argv++, OREAD)) == -1){ 36 if(!sflag) perror(name2); 37 exits("open"); 38 } 39 if(*argv){ 40 o = strtoll(*argv++, 0, 0); 41 if(seek(f1, o, 0) < 0){ 42 if(!sflag) perror("cmp: seek by offset1"); 43 exits("seek 1"); 44 } 45 } 46 if(*argv){ 47 o = strtoll(*argv++, 0, 0); 48 if(seek(f2, o, 0) < 0){ 49 if(!sflag) perror("cmp: seek by offset2"); 50 exits("seek 2"); 51 } 52 } 53 if(*argv) 54 usage(); 55 b1s = b1e = buf1; 56 b2s = b2e = buf2; 57 for(;;){ 58 if(b1s >= b1e){ 59 if(b1s >= &buf1[BUF]) 60 b1s = buf1; 61 n = read(f1, b1s, &buf1[BUF] - b1s); 62 b1e = b1s + n; 63 } 64 if(b2s >= b2e){ 65 if(b2s >= &buf2[BUF]) 66 b2s = buf2; 67 n = read(f2, b2s, &buf2[BUF] - b2s); 68 b2e = b2s + n; 69 } 70 n = b2e - b2s; 71 if(n > b1e - b1s) 72 n = b1e - b1s; 73 if(n <= 0) 74 break; 75 if(memcmp((void *)b1s, (void *)b2s, n) != 0){ 76 if(sflag) 77 exits("differ"); 78 for(p = b1s, q = b2s, i = 0; i < n; p++, q++, i++) { 79 if(*p == '\n') 80 l++; 81 if(*p != *q){ 82 if(!lflag){ 83 print("%s %s differ: char %lld", 84 name1, name2, nc+i); 85 print(Lflag?" line %lld\n":"\n", l); 86 exits("differ"); 87 } 88 print("%6lld 0x%.2x 0x%.2x\n", nc+i, *p, *q); 89 } 90 } 91 } 92 if(Lflag) 93 for(p = b1s; p < b1e;) 94 if(*p++ == '\n') 95 l++; 96 nc += n; 97 b1s += n; 98 b2s += n; 99 } 100 if(b1e - b1s == b2e - b2s) 101 exits((char *)0); 102 if(!sflag) 103 print("EOF on %s\n", (b1e - b1s > b2e - b2s)? name2 : name1); 104 exits("EOF"); 105 } 106 107 static void 108 usage(void) 109 { 110 print("Usage: cmp [-lsL] file1 file2 [offset1 [offset2] ]\n"); 111 exits("usage"); 112 }