better handling of whole files
[tridge/junkcode.git] / lcmp.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <time.h>
4 #include <fcntl.h>
5 #include <sys/stat.h>
6 #include <stdlib.h>
7 #include <errno.h>
8
9 int main(int argc, char *argv[])
10 {
11         int fd1, fd2;
12         char *buf1, *buf2;
13         int bufsize = 1024*1024;
14         off_t offset;
15
16         if (argc < 3) {
17                 printf("usage: lcmp <file1> <file2>\n");
18                 exit(1);
19         }
20
21         fd1 = open(argv[1], O_RDONLY);
22         fd2 = open(argv[2], O_RDONLY);
23
24         buf1 = malloc(bufsize);
25         buf2 = malloc(bufsize);
26
27         offset = 0;
28
29         while (1) {
30                 int n1, n2, n, i;
31
32                 printf("%.0f\r", (double)offset);
33                 fflush(stdout);
34
35                 n1 = read(fd1, buf1, bufsize);
36                 n2 = read(fd2, buf2, bufsize);
37
38                 n = n1;
39                 if (n2 < n1) n = n2;
40
41                 if (memcmp(buf1, buf2, n)) {
42                         for (i=0;i<n;i++)
43                                 if (buf1[i] != buf2[i]) {
44                                         printf("%s and %s differ at offset %.0f\n",
45                                                argv[1], argv[2], (double)(offset+i));
46                                         exit(1);
47                                 }
48                 }
49
50                 if (n1 < n2) {
51                         printf("EOF on %s\n", argv[1]);
52                         exit(1);
53                 }
54                 if (n2 < n1) {
55                         printf("EOF on %s\n", argv[2]);
56                         exit(1);
57                 }
58
59                 offset += n;
60
61                 if (n == 0) break;
62         }
63
64         free(buf1);
65         free(buf2);
66         close(fd1);
67         close(fd2);
68         return 0;
69 }