retire nonsymbolic rootdev, dev2name
[minix.git] / commands / cmp / cmp.c
blob88efac68973ca49b93239df5de503c1bdde76a53
1 /* cmp - compare two files Author: Kees J. Bot. */
3 #include <sys/types.h>
4 #include <fcntl.h>
5 #include <stdlib.h>
6 #include <unistd.h>
7 #include <stdio.h>
8 #include <string.h>
9 #include <errno.h>
11 void fatal(char *label);
12 int cmp(int fd1, int fd2);
13 void Usage(void);
14 int main(int argc, char **argv);
16 #define BLOCK 4096
18 static int loud = 0, silent = 0;
19 static char *name1, *name2;
21 int main(argc, argv)
22 int argc;
23 char **argv;
25 int fd1, fd2;
27 /* Process the '-l' or '-s' option. */
28 while (argc > 1 && argv[1][0] == '-' && argv[1][1] != 0) {
29 if (argv[1][2] != 0) Usage();
31 switch (argv[1][1]) {
32 case '-':
33 /* '--': no-op option. */
34 break;
35 case 'l':
36 loud = 1;
37 break;
38 case 's':
39 silent = 1;
40 break;
41 default:
42 Usage();
44 argc--;
45 argv++;
47 if (argc != 3) Usage();
49 /* Open the first file, '-' means standard input. */
50 if (argv[1][0] == '-' && argv[1][1] == 0) {
51 name1 = "stdin";
52 fd1 = 0;
53 } else {
54 name1 = argv[1];
55 if ((fd1 = open(name1, 0)) < 0) fatal(name1);
58 /* Second file likewise. */
59 if (argv[2][0] == '-' && argv[2][1] == 0) {
60 name2 = "stdin";
61 fd2 = 0;
62 } else {
63 name2 = argv[2];
64 if ((fd2 = open(name2, 0)) < 0) fatal(name2);
67 exit(cmp(fd1, fd2));
70 int cmp(fd1, fd2)
71 int fd1, fd2;
73 static char buf1[BLOCK], buf2[BLOCK];
74 int n1 = 0, n2 = 0, i1 = 0, i2 = 0, c1, c2;
75 off_t pos = 0, line = 1;
76 int eof = 0, differ = 0;
78 for (;;) {
79 if (i1 == n1) {
80 pos += n1;
82 if ((n1 = read(fd1, buf1, sizeof(buf1))) <= 0) {
83 if (n1 < 0) fatal(name1);
84 eof |= 1;
86 i1 = 0;
88 if (i2 == n2) {
89 if ((n2 = read(fd2, buf2, sizeof(buf2))) <= 0) {
90 if (n2 < 0) fatal(name2);
91 eof |= 2;
93 i2 = 0;
95 if (eof != 0) break;
97 c1 = buf1[i1++];
98 c2 = buf2[i2++];
100 if (c1 != c2) {
101 if (!loud) {
102 if (!silent) {
103 printf("%s %s differ: char %ld, line %ld\n",
104 name1, name2, pos + i1, line);
106 return(1);
108 printf("%10ld %3o %3o\n", pos + i1, c1 & 0xFF, c2 & 0xFF);
109 differ = 1;
111 if (c1 == '\n') line++;
113 if (eof == (1 | 2)) return(differ);
114 if (!silent) fprintf(stderr, "cmp: EOF on %s\n", eof == 1 ? name1 : name2);
115 return(1);
118 void fatal(label)
119 char *label;
121 if (!silent) fprintf(stderr, "cmp: %s: %s\n", label, strerror(errno));
122 exit(2);
125 void Usage()
127 fprintf(stderr, "Usage: cmp [-l | -s] file1 file2\n");
128 exit(2);