aboutsummaryrefslogtreecommitdiffstats
path: root/usr/cmp.c
blob: 5a4a71857a694adf066636893cd2fc4410dd4c74 (plain) (blame)
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
#include "gbos.h"
/* cmp FILE1 FILE2: report the first byte where two files differ, or say
 * nothing when they match (like cmp(1), silence means identical).
 *
 * After cp/mv/tee/nc there was still no way to check a copy ON the machine -
 * you had to haul both files to a host. */
void main(void) {
    char *argv[4];
    unsigned char argc = argv_parse(argv, 4);
    unsigned char a, b;
    unsigned int off = 0;
    int ca, cb;

    if (argc < 2) {
        puts("usage: cmp FILE1 FILE2");
        nl();
        sexit(2);
    }
    a = open(argv[0], O_READ);
    if (a > 3) {
        puts("cmp: cannot open ");
        puts(argv[0]);
        nl();
        sexit(2);
    }
    b = open(argv[1], O_READ);
    if (b > 3) {
        puts("cmp: cannot open ");
        puts(argv[1]);
        nl();
        close(a);
        sexit(2);
    }

    for (;;) {
        ca = fgetc(a);
        cb = fgetc(b);
        if (ca < 0 && cb < 0) break; /* same length, same bytes */
        if (ca < 0 || cb < 0) {
            puts("cmp: EOF on ");
            puts(ca < 0 ? argv[0] : argv[1]);
            puts(" after ");
            putu(off);
            nl();
            close(a);
            close(b);
            sexit(1);
        }
        if (ca != cb) {
            puts("differ: byte ");
            putu(off);
            nl();
            close(a);
            close(b);
            sexit(1);
        }
        off++;
    }
    close(a);
    close(b);
}