Implementations of common Unix command-line utilities written in C.
unix-tools / grep.c
| 1 | #define _POSIX_C_SOURCE 200809L |
| 2 | #include <stdio.h> |
| 3 | #include <stdlib.h> |
| 4 | #include <string.h> |
| 5 | #include <sys/types.h> |
| 6 | |
| 7 | static int |
| 8 | search(FILE *file, const char *pattern, const char *name) |
| 9 | { |
| 10 | char *line = NULL; |
| 11 | size_t capacity = 0; |
| 12 | size_t pattern_len = strlen(pattern); |
| 13 | ssize_t n; |
| 14 | int matched = 0; |
| 15 | while ((n = getline(&line, &capacity, file)) >= 0) { |
| 16 | size_t i; |
| 17 | if (pattern_len > (size_t)n) continue; |
| 18 | for (i = 0; i <= (size_t)n - pattern_len; ++i) |
| 19 | if (memcmp(line + i, pattern, pattern_len) == 0) break; |
| 20 | if (i > (size_t)n - pattern_len) continue; |
| 21 | if (fwrite(line, 1, (size_t)n, stdout) != (size_t)n) { |
| 22 | perror("grep: stdout"); free(line); return 2; |
| 23 | } |
| 24 | matched = 1; |
| 25 | } |
| 26 | free(line); |
| 27 | if (!feof(file)) { perror(name); return 2; } |
| 28 | return matched ? 0 : 1; |
| 29 | } |
| 30 | |
| 31 | int |
| 32 | main(int argc, char **argv) |
| 33 | { |
| 34 | int i, status = 1; |
| 35 | if (argc < 2) { fprintf(stderr, "usage: %s pattern [file...]\n", argv[0]); return 2; } |
| 36 | if (argc == 2) status = search(stdin, argv[1], "grep: stdin"); |
| 37 | for (i = 2; i < argc; ++i) { |
| 38 | FILE *file = strcmp(argv[i], "-") == 0 ? stdin : fopen(argv[i], "r"); |
| 39 | int result; |
| 40 | if (file == NULL) { perror(argv[i]); status = 2; continue; } |
| 41 | result = search(file, argv[1], argv[i]); |
| 42 | if (result == 2) status = 2; |
| 43 | else if (result == 0 && status != 2) status = 0; |
| 44 | if (file != stdin && fclose(file) == EOF) { perror(argv[i]); status = 2; } |
| 45 | } |
| 46 | if (fflush(stdout) == EOF) { perror("grep: stdout"); status = 2; } |
| 47 | return status; |
| 48 | } |