aboutsummaryrefslogtreecommitdiff
path: root/src/cmd/cmp.c
blob: 4f69e181597666c8855656231c2d7baefa32d7a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <u.h>
#include <libc.h>

#define		BUF		65536

int sflag = 0;
int lflag = 0;
int Lflag = 0;

static void usage(void);

void
main(int argc, char *argv[])
{
	int n, i;
	uchar *p, *q;
	uchar buf1[BUF], buf2[BUF];
	int f1, f2;
	vlong nc = 1, o, l = 1;
	char *name1, *name2;
	uchar *b1s, *b1e, *b2s, *b2e;

	ARGBEGIN{
	case 's':	sflag = 1; break;
	case 'l':	lflag = 1; break;
	case 'L':	Lflag = 1; break;
	default:	usage();
	}ARGEND
	if(argc < 2)
		usage();
	if((f1 = open(name1 = *argv++, OREAD)) == -1){
		if(!sflag) perror(name1);
		exits("open");
	}
	if((f2 = open(name2 = *argv++, OREAD)) == -1){
		if(!sflag) perror(name2);
		exits("open");
	}
	if(*argv){
		o = strtoll(*argv++, 0, 0);
		if(seek(f1, o, 0) < 0){
			if(!sflag) perror("cmp: seek by offset1");
			exits("seek 1");
		}
	}
	if(*argv){
		o = strtoll(*argv++, 0, 0);
		if(seek(f2, o, 0) < 0){
			if(!sflag) perror("cmp: seek by offset2");
			exits("seek 2");
		}
	}
	if(*argv)
		usage();
	b1s = b1e = buf1;
	b2s = b2e = buf2;
	for(;;){
		if(b1s >= b1e){
			if(b1s >= &buf1[BUF])
				b1s = buf1;
			n = read(f1, b1s,  &buf1[BUF] - b1s);
			b1e = b1s + n;
		}
		if(b2s >= b2e){
			if(b2s >= &buf2[BUF])
				b2s = buf2;
			n = read(f2, b2s,  &buf2[BUF] - b2s);
			b2e = b2s + n;
		}
		n = b2e - b2s;
		if(n > b1e - b1s)
			n = b1e - b1s;
		if(n <= 0)
			break;
		if(memcmp((void *)b1s, (void *)b2s, n) != 0){
			if(sflag)
				exits("differ");
			for(p = b1s, q = b2s, i = 0; i < n; p++, q++, i++) {
				if(*p == '\n')
					l++;
				if(*p != *q){
					if(!lflag){
						print("%s %s differ: char %lld",
						    name1, name2, nc+i);
						print(Lflag?" line %lld\n":"\n", l);
						exits("differ");
					}
					print("%6lld 0x%.2x 0x%.2x\n", nc+i, *p, *q);
				}
			}
		}		
		if(Lflag)
			for(p = b1s; p < b1e;)
				if(*p++ == '\n')
					l++;
		nc += n;
		b1s += n;
		b2s += n;
	}
	if(b1e - b1s == b2e - b2s)
		exits((char *)0);
	if(!sflag)
		print("EOF on %s\n", (b1e - b1s > b2e - b2s)? name2 : name1);
	exits("EOF");
}

static void
usage(void)
{
	print("Usage: cmp [-lsL] file1 file2 [offset1 [offset2] ]\n");
	exits("usage");
}