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
|
/* Calculates the xor of two files.
* Copyright (C) 2013 Peter Wu <lekensteyn@gmail.com>
*/
#include <err.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int open_file(const char *filename) {
int fd;
if (!strcmp(filename, "-"))
return STDIN_FILENO;
fd = open(filename, O_RDONLY);
if (fd < 0)
errx(1, "open(%s)", filename);
return fd;
}
int main(int argc, char **argv) {
int fd1, fd2;
int r1, r2;
if (argc < 3)
errx(1, "Usage: xor-files file1 file2");
fd1 = open_file(argv[1]);
fd2 = open_file(argv[2]);
do {
int errno1, errno2;
char buf1[1024], buf2[1024];
int i;
r1 = read(fd1, buf1, sizeof(buf1));
errno1 = errno;
r2 = read(fd2, buf2, sizeof(buf2));
errno2 = errno;
if (r1 == -1) {
errno = errno1;
warn("read 1 failed");
}
if (r2 == -1) {
errno = errno2;
warn("read 2 failed");
}
if (r1 != r2)
warnx("read blocks do not match: %i != %i", r1, r2);
// in case the sizes are not equal, truncate.
if (r2 < r1)
r1 = r2;
if (r1 > 0) {
for (i = 0; i < r1; i++)
buf1[i] ^= buf2[i];
write(STDOUT_FILENO, buf1, r1);
}
} while (r1 > 0 && r1 == r2);
close(fd1);
close(fd2);
return 0;
}
|