-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrep.cpp
More file actions
99 lines (89 loc) · 1.95 KB
/
grep.cpp
File metadata and controls
99 lines (89 loc) · 1.95 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
#include "regex.h"
#include <cstdio>
#include <cstring>
int main(int argc, char *argv[])
{
int i, nmatch;
FILE *f;
Options opts;
if (argc < 2) {
fprintf(stderr, "usage: grep regexp [option ...] [file ...]");
}
nmatch = 0;
for (i = 1; i < argc && argv[i][0] == '-'; i++) {
if (strlen(argv[i]) < 2) {
fprintf(stderr, "usage: grep [option ...] regexp [file ...]");
} else {
for (size_t j = 0; j < strlen(argv[i]); j++) {
switch (argv[i][j])
{
case 'i':
opts.caseinsensitive = true;
break;
case 'v':
opts.negate = true;
break;
case 'n':
opts.printlinenumbers = true;
default:
break;
}
}
}
}
if (i == argc) {
fprintf(stderr, "usage: grep [option ...] regexp [file ...]");
}
char *pattern = argv[i++];
if (i == argc) {
if (grep(pattern, stdin, NULL, opts)) {
nmatch++;
}
} else {
int nfiles = argc - i;
for (; i < argc; i++)
{
f = fopen(argv[i], "r");
if (f == NULL) {
printf("WARNING: Can't open %s:", argv[i]);
continue;
}
if (grep(pattern, f, nfiles > 1 ? argv[i] : NULL, opts) > 0) {
nmatch++;
}
fclose(f);
}
}
return opts.negate ? nmatch != 0 : nmatch == 0;
}
int grep(char *regexp, FILE *f, char *name, Options opts) {
int n, nmatch;
char buf[BUFSIZ];
nmatch = 0;
int lnumber = 0;
while (fgets(buf, sizeof buf, f) != NULL)
{
n = strlen(buf);
if (n > 0 && buf[n-1] == '\n') {
buf[n-1] = '\0';
}
if (buf[n - 1] == '\0' || feof(f))
{
lnumber++;
}
if (match(regexp, buf, opts)) {
nmatch++;
if (opts.negate) {
continue;
}
if (name != NULL) {
printf("%s:", name);
}
if (opts.printlinenumbers) {
printf("%d:", lnumber);
}
printf("%s\n", buf);
}
}
return nmatch;
}