-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -15,6 +15,7 @@ BIN_TARGET_NAMES := \ | |
env \ | ||
eyes \ | ||
fib \ | ||
grep \ | ||
halt \ | ||
imgview \ | ||
init \ | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
// grep - print lines matching a pattern | ||
#include <fcntl.h> | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
#include <string.h> | ||
#include <sys/stat.h> | ||
#include <unistd.h> | ||
|
||
int main(int argc, char* const argv[]) { | ||
if (argc < 2) { | ||
dprintf(STDERR_FILENO, "Usage: grep PATTERN [FILE]...\n"); | ||
return EXIT_FAILURE; | ||
} | ||
|
||
const char* pattern = argv[1]; | ||
|
||
for (int i = 2; i < argc; i++) { | ||
const char* filename = argv[i]; | ||
|
||
struct stat st; | ||
if (stat(filename, &st) < 0) { | ||
perror("stat"); | ||
return EXIT_FAILURE; | ||
} | ||
|
||
char* buf = malloc(st.st_size + 1); // +1 for null terminator | ||
if (!buf) { | ||
perror("malloc"); | ||
return EXIT_FAILURE; | ||
} | ||
|
||
int fd = open(filename, O_RDONLY); | ||
if (fd < 0) { | ||
perror("open"); | ||
goto done; | ||
} | ||
|
||
size_t cursor = 0; | ||
ssize_t nread; | ||
while ((nread = read(fd, buf + cursor, st.st_size - cursor)) > 0) | ||
cursor += nread; | ||
if (nread < 0) { | ||
perror("read"); | ||
goto done; | ||
} | ||
close(fd); | ||
fd = -1; | ||
buf[cursor] = 0; | ||
|
||
static const char* sep = "\n"; | ||
char* saved_ptr; | ||
for (char* line = strtok_r(buf, sep, &saved_ptr); line; | ||
line = strtok_r(NULL, sep, &saved_ptr)) { | ||
if (strstr(line, pattern)) { | ||
if (argc > 3) | ||
printf("%s:%s\n", filename, line); | ||
else | ||
puts(line); | ||
} | ||
} | ||
|
||
done: | ||
free(buf); | ||
if (fd >= 0) | ||
close(fd); | ||
} | ||
|
||
return EXIT_SUCCESS; | ||
} |