-
Notifications
You must be signed in to change notification settings - Fork 0
/
grep.c
43 lines (40 loc) · 849 Bytes
/
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
int main(int argc, char **argv){
int status, i, r;
size_t n;
int cflag = REG_EXTENDED|REG_NEWLINE;
regmatch_t match;
regex_t reg;
char *buf = NULL;
if(argc >= 2){
regcomp(®, argv[1], cflag);
while((r = getline(&buf, &n, stdin) != -1)){
char *tmp = buf;
bzero(&match, sizeof(match));
while(1){
tmp += match.rm_eo;
status = regexec(®, tmp, 1, &match, 0);
if(status == REG_NOMATCH)
break;
else if(status == 0){
for(i = 0; i < match.rm_so; ++i){
putchar(tmp[i]);
}
printf("\033[1;31m");
for(i = match.rm_so; i < match.rm_eo; ++i){
putchar(tmp[i]);
}
printf("\033[0m");
}
}
if(tmp != buf) printf("%s", tmp);
free(buf);
buf = NULL;
}
regfree(®);
}
return 0;
}