2024-07-01 10:23:00 +00:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
#include <regex.h>
|
|
|
|
|
|
|
|
typedef struct {
|
|
|
|
char *pattern;
|
|
|
|
regex_t rgex;
|
|
|
|
} PATTERN;
|
2024-07-09 12:43:55 +00:00
|
|
|
static PATTERN *regexs;
|
|
|
|
static size_t r_size;
|
2024-07-01 10:23:00 +00:00
|
|
|
|
2024-07-09 12:43:55 +00:00
|
|
|
static int addpattern(char *str) {
|
2024-07-01 10:23:00 +00:00
|
|
|
if (regexs == NULL) {
|
|
|
|
regexs = malloc(sizeof(PATTERN));
|
|
|
|
if (regexs == NULL) {
|
|
|
|
fprintf(stderr, "grep: malloc failed\n");
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
PATTERN *regexs_tmp = realloc(regexs, (r_size + 1) * sizeof(PATTERN));
|
|
|
|
if (regexs_tmp == NULL) {
|
|
|
|
free(regexs);
|
|
|
|
|
|
|
|
fprintf(stderr, "grep: realloc failed\n");
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
regexs = regexs_tmp;
|
|
|
|
|
|
|
|
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] [FILE]\n\t-e PTRN Pattern to match\n");
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
argv += optind;
|
|
|
|
argc -= optind;
|
|
|
|
if (r_size == 0) {
|
|
|
|
fprintf(stderr, "grep: no patterns specified\n");
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
free(regexs);
|
|
|
|
return 0;
|
|
|
|
}
|