-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgrep.c
More file actions
118 lines (106 loc) · 2.06 KB
/
grep.c
File metadata and controls
118 lines (106 loc) · 2.06 KB
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
/* See LICENSE file for copyright and license details. */
#include <regex.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "text.h"
#include "util.h"
enum { Match = 0, NoMatch = 1, Error = 2 };
static void grep(FILE *, const char *, regex_t *);
static void usage(void);
static bool vflag = false;
static bool many;
static bool match = false;
static char mode = 0;
static char delim = '\n';
int
main(int argc, char *argv[])
{
int i, n, flags = REG_NOSUB;
regex_t preg;
FILE *fp;
ARGBEGIN {
case 'E':
flags |= REG_EXTENDED;
break;
case 'c':
case 'l':
case 'n':
case 'q':
mode = ARGC();
break;
case 'i':
flags |= REG_ICASE;
break;
case 'v':
vflag = true;
break;
case 'z':
delim = '\0';
break;
default:
usage();
} ARGEND;
if(argc == 0)
usage(); /* no pattern */
if((n = regcomp(&preg, argv[0], flags)) != 0) {
char buf[BUFSIZ];
regerror(n, &preg, buf, sizeof buf);
enprintf(Error, "invalid pattern: %s\n", buf);
}
many = (argc > 1);
if(argc == 1)
grep(stdin, "<stdin>", &preg);
else for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "-") == 0) argv[i] = "/dev/stdin";
if(!(fp = fopen(argv[i], "r")))
enprintf(Error, "fopen %s:", argv[i]);
grep(fp, argv[i], &preg);
fclose(fp);
}
return match ? Match : NoMatch;
}
void
grep(FILE *fp, const char *str, regex_t *preg)
{
char *buf = NULL;
long n, c = 0;
size_t size = 0, len;
for(n = 1; getdelim(&buf, &size, delim, fp) >= 0; n++) {
if(buf[(len = strlen(buf))-1] == '\n')
buf[--len] = '\0';
if(regexec(preg, buf, 0, NULL, 0) ^ vflag)
continue;
switch(mode) {
case 'c':
c++;
break;
case 'l':
puts(str);
goto end;
case 'q':
exit(Match);
default:
if(many)
printf("%s:", str);
if(mode == 'n')
printf("%ld:", n);
printf("%s%c", buf, delim);
break;
}
match = true;
}
if(mode == 'c')
printf("%ld\n", c);
end:
if(ferror(fp))
enprintf(Error, "%s: read error:", str);
free(buf);
}
void
usage(void)
{
enprintf(Error, "usage: %s [-Ecilnqv] pattern [files...]\n", argv0);
}