434
|
1 /* vi: set sw=4 ts=4:
|
|
2 *
|
|
3 * cmp.c - Compare two files.
|
|
4 *
|
|
5 * Copyright 2012 Timothy Elliott <tle@holymonkey.com>
|
|
6 *
|
|
7 * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/cmp.html
|
|
8
|
|
9 USE_CMP(NEWTOY(cmp, "<2>2ls", TOYFLAG_USR|TOYFLAG_BIN))
|
|
10
|
|
11 config CMP
|
|
12 bool "cmp"
|
|
13 default y
|
|
14 help
|
|
15 usage: cmp [-l] [-s] FILE1 FILE2
|
|
16
|
|
17 Compare the contents of two files.
|
|
18
|
|
19 -l show all differing bytes
|
|
20 -s silent
|
|
21 */
|
|
22
|
|
23 #include "toys.h"
|
|
24
|
|
25 #define FLAG_s 1
|
|
26 #define FLAG_l 2
|
|
27
|
|
28 int get_fd(char *file)
|
|
29 {
|
|
30 int fd;
|
|
31
|
|
32 if (!strcmp(file,"-")) fd=0;
|
|
33 else if (0>(fd = open(file, O_RDONLY, 0))) {
|
|
34 perror_exit("%s", file);
|
|
35 }
|
|
36 return fd;
|
|
37 }
|
|
38
|
|
39 void do_cmp(int fd1, int fd2, char *file1, char *file2, char *buf1, char *buf2,
|
|
40 size_t size) {
|
|
41 int i, len1, len2, min_len;
|
|
42 size_t byte_no = 1, line_no = 1;
|
|
43
|
|
44 for (;;) {
|
|
45 len1 = read(fd1, buf1, size);
|
|
46 len2 = read(fd2, buf2, size);
|
|
47
|
|
48 min_len = len1 < len2 ? len1 : len2;
|
|
49 for (i=0; i<min_len; i++) {
|
|
50 if (buf1[i] != buf2[i]) {
|
|
51 toys.exitval = 1;
|
|
52 if (toys.optflags & FLAG_l) {
|
|
53 printf("%d %o %o\n", byte_no, buf1[i],
|
|
54 buf2[i]);
|
|
55 }
|
|
56 else {
|
|
57 if (!(toys.optflags & FLAG_s)) {
|
|
58 printf("%s %s differ: char %d, line %d\n",
|
|
59 file1, file2, byte_no,
|
|
60 line_no);
|
|
61 }
|
|
62 return;
|
|
63 }
|
|
64
|
|
65 }
|
|
66 byte_no++;
|
|
67 if (buf1[i] == '\n') line_no++;
|
|
68 }
|
|
69 if (len1 != len2) {
|
|
70 if (!(toys.optflags & FLAG_s)) {
|
|
71 fdprintf(2, "cmp: EOF on %s\n",
|
|
72 len1 < len2 ? file1 : file2);
|
|
73 }
|
|
74 toys.exitval = 1;
|
|
75 break;
|
|
76 }
|
|
77 if (len1 < 1) break;
|
|
78 }
|
|
79 }
|
|
80
|
|
81 void cmp_main(void)
|
|
82 {
|
|
83 char *file1 = toys.optargs[0];
|
|
84 char *file2 = toys.optargs[1];
|
|
85 int fd1, fd2, size=sizeof(toybuf);
|
|
86 char *toybuf2 = xmalloc(size);
|
|
87
|
|
88 fd1 = get_fd(file1);
|
|
89 fd2 = get_fd(file2);
|
|
90
|
|
91 do_cmp(fd1, fd2, file1, file2, toybuf, toybuf2, size);
|
|
92
|
|
93 close(fd1);
|
|
94 close(fd2);
|
|
95 free(toybuf2);
|
|
96 }
|
|
97
|