micro-utils/src/findutils/grep/grep.c

63 lines
989 B
C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <regex.h>
typedef struct {
char *pattern;
regex_t rgex;
} PATTERN;
PATTERN *regexs;
size_t r_size;
int addpattern(char *str) {
if (regexs == NULL) {
regexs = malloc(sizeof(PATTERN));
if (regexs == NULL) {
fprintf(stderr, "grep: malloc failed\n");
return 1;
}
}
regexs = realloc(regexs, (r_size + 1) * sizeof(PATTERN));
if (regexs == NULL) {
fprintf(stderr, "grep: malloc failed\n");
return 1;
}
regexs[r_size].pattern = str;
r_size++;
return 0;
}
int main(int argc, char **argv) {
int opt;
while ((opt = getopt(argc, argv, "e:")) != -1) {
switch (opt) {
case 'e':
if (addpattern(optarg))
return 1;
break;
default:
printf("grep [e] [PATTERN | -e PATTERN] [FILE]\n");
return 0;
}
}
argv += optind;
argc -= optind;
if (r_size == 0) {
fprintf(stderr, "grep: no patterns specified\n");
return 1;
}
free(regexs);
return 0;
}