1 /* cmp.c - Compare two files.
3 * Copyright 2012 Timothy Elliott <tle@holymonkey.com>
5 * See http://opengroup.org/onlinepubs/9699919799/utilities/cmp.html
7 USE_CMP(NEWTOY(cmp, "<2>2ls", TOYFLAG_USR|TOYFLAG_BIN))
13 usage: cmp [-l] [-s] FILE1 FILE2
15 Compare the contents of two files.
17 -l show all differing bytes
29 // This handles opening the file and
31 void do_cmp(int fd, char *name)
33 int i, len1, len2, min_len, size = sizeof(toybuf)/2;
34 long byte_no = 1, line_no = 1;
35 char *buf2 = toybuf+size;
37 // First time through, cache the data and return.
40 // On return the old filehandle is closed, and this assures that even
41 // if we were called with stdin closed, the new filehandle != 0.
47 len1 = readall(TT.fd, toybuf, size);
48 len2 = readall(fd, buf2, size);
50 min_len = len1 < len2 ? len1 : len2;
51 for (i=0; i<min_len; i++) {
52 if (toybuf[i] != buf2[i]) {
54 if (toys.optflags & FLAG_l)
55 printf("%ld %o %o\n", byte_no, toybuf[i], buf2[i]);
57 if (!(toys.optflags & FLAG_s)) {
58 printf("%s %s differ: char %ld, line %ld\n",
59 TT.name, name, byte_no, line_no);
66 if (toybuf[i] == '\n') line_no++;
69 if (!(toys.optflags & FLAG_s))
70 fprintf(stderr, "cmp: EOF on %s\n", len1 < len2 ? TT.name : name);
77 if (CFG_TOYBOX_FREE) close(TT.fd);
82 loopfiles_rw(toys.optargs, O_CLOEXEC, 0, toys.optflags&FLAG_s, do_cmp);