-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgrep.c
68 lines (55 loc) · 1.14 KB
/
grep.c
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
#include "type.h"
#include "ucode.c"
#define N_BUF 1024
char* pattern, buf[N_BUF];
int main(int argc, char* argv[])
{
char c;
int i, r, fd;
int match, pat_len, line_len, size_left;
STAT s;
pattern = argv[1];
pat_len = strlen(pattern);
if(1 == argc) {
printf("USAGE: grep pattern [filename]\n");
exit(-1);
}
write(STDERR, "[===== IFM grep =====]\n\r", 24);
// if available, use filename as input
if(argc > 2) {
stat(argv[2], &s);
if(0 < s.st_size) {
fd = open(argv[2], O_RDONLY);
size_left = s.st_size;
}
else {
printf("ERR: %s does not exist\n", argv[2]);
exit(-1);
}
}
else {
fd = STDIN;
size_left = -1; // no size for stdin
}
while(-1 != c && 0 != size_left)
{
match = 0;
i = 0;
do {
read(fd, &c, 1);
buf[i] = c;
i++;
size_left--;
} while( (i < (N_BUF-1)) && (-1 != c) && ('\r' != c) && (size_left != 0) );
buf[i] = 0;
line_len = strlen(buf);
for(i=0; i<(line_len-pat_len); i++) {
if(0==strncmp(pattern, buf+i, pat_len)) {
match = 1;
break;
}
}
if(match)
printf("%s", buf);
}
}