source: trunk/minix/commands/simple/cmp.c@ 10

Last change on this file since 10 was 9, checked in by Mattia Monga, 13 years ago

Minix 3.1.2a

File size: 2.3 KB
Line 
1/* cmp - compare two files Author: Kees J. Bot. */
2
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>
10
11_PROTOTYPE(void fatal, (char *label));
12_PROTOTYPE(int cmp, (int fd1, int fd2));
13_PROTOTYPE(void Usage, (void));
14_PROTOTYPE(int main, (int argc, char **argv));
15
16#define BLOCK 4096
17
18static int loud = 0, silent = 0;
19static char *name1, *name2;
20
21int main(argc, argv)
22int argc;
23char **argv;
24{
25 int fd1, fd2;
26
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();
30
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();
43 }
44 argc--;
45 argv++;
46 }
47 if (argc != 3) Usage();
48
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);
56 }
57
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);
65 }
66
67 exit(cmp(fd1, fd2));
68}
69
70int cmp(fd1, fd2)
71int fd1, fd2;
72{
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;
77
78 for (;;) {
79 if (i1 == n1) {
80 pos += n1;
81
82 if ((n1 = read(fd1, buf1, sizeof(buf1))) <= 0) {
83 if (n1 < 0) fatal(name1);
84 eof |= 1;
85 }
86 i1 = 0;
87 }
88 if (i2 == n2) {
89 if ((n2 = read(fd2, buf2, sizeof(buf2))) <= 0) {
90 if (n2 < 0) fatal(name2);
91 eof |= 2;
92 }
93 i2 = 0;
94 }
95 if (eof != 0) break;
96
97 c1 = buf1[i1++];
98 c2 = buf2[i2++];
99
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);
105 }
106 return(1);
107 }
108 printf("%10ld %3o %3o\n", pos + i1, c1 & 0xFF, c2 & 0xFF);
109 differ = 1;
110 }
111 if (c1 == '\n') line++;
112 }
113 if (eof == (1 | 2)) return(differ);
114 if (!silent) fprintf(stderr, "cmp: EOF on %s\n", eof == 1 ? name1 : name2);
115 return(1);
116}
117
118void fatal(label)
119char *label;
120{
121 if (!silent) fprintf(stderr, "cmp: %s: %s\n", label, strerror(errno));
122 exit(2);
123}
124
125void Usage()
126{
127 fprintf(stderr, "Usage: cmp [-l | -s] file1 file2\n");
128 exit(2);
129}
Note: See TracBrowser for help on using the repository browser.