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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
|
#include <u.h>
#include <libc.h>
#include <bio.h>
#define LB 2048
int one;
int two;
int three;
char ldr[3][4] = { "", "\t", "\t\t" };
Biobuf *ib1;
Biobuf *ib2;
Biobuf *openfil(char*);
int rd(Biobuf*, char*);
void wr(char*, int);
void copy(Biobuf*, char*, int);
int compare(char*, char*);
void
main(int argc, char *argv[])
{
int l;
char lb1[LB],lb2[LB];
l = 2;
ARGBEGIN{
case '1':
if(!one) {
one = 1;
ldr[1][0] =
ldr[2][l--] = '\0';
}
break;
case '2':
if(!two) {
two = 1;
ldr[2][l--] = '\0';
}
break;
case '3':
three = 1;
break;
default:
goto Usage;
}ARGEND
if(argc < 2) {
Usage:
fprint(2, "usage: comm [-123] file1 file2\n");
exits("usage");
}
ib1 = openfil(argv[0]);
ib2 = openfil(argv[1]);
if(rd(ib1,lb1) < 0){
if(rd(ib2,lb2) < 0)
exits(0);
copy(ib2,lb2,2);
}
if(rd(ib2,lb2) < 0)
copy(ib1,lb1,1);
for(;;){
switch(compare(lb1,lb2)) {
case 0:
wr(lb1,3);
if(rd(ib1,lb1) < 0) {
if(rd(ib2,lb2) < 0)
exits(0);
copy(ib2,lb2,2);
}
if(rd(ib2,lb2) < 0)
copy(ib1,lb1,1);
continue;
case 1:
wr(lb1,1);
if(rd(ib1,lb1) < 0)
copy(ib2,lb2,2);
continue;
case 2:
wr(lb2,2);
if(rd(ib2,lb2) < 0)
copy(ib1,lb1,1);
continue;
}
}
exits(0);
}
int
rd(Biobuf *file, char *buf)
{
int i, c;
i = 0;
while((c = Bgetc(file)) != Beof) {
*buf = c;
if(c == '\n' || i > LB-2) {
*buf = '\0';
return 0;
}
i++;
buf++;
}
return -1;
}
void
wr(char *str, int n)
{
switch(n){
case 1:
if(one)
return;
break;
case 2:
if(two)
return;
break;
case 3:
if(three)
return;
}
print("%s%s\n", ldr[n-1],str);
}
void
copy(Biobuf *ibuf, char *lbuf, int n)
{
do
wr(lbuf,n);
while(rd(ibuf,lbuf) >= 0);
exits(0);
}
int
compare(char *a, char *b)
{
while(*a == *b){
if(*a == '\0')
return 0;
a++;
b++;
}
if(*a < *b)
return 1;
return 2;
}
Biobuf*
openfil(char *s)
{
Biobuf *b;
if(s[0]=='-' && s[1]==0)
s = "/fd/0";
b = Bopen(s, OREAD);
if(b)
return b;
fprint(2,"comm: cannot open %s: %r\n",s);
exits("open");
return 0; /* shut up ken */
}
|