micro-utils/src/grep.c

81 lines
1.3 KiB
C
Raw Normal View History

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 19:33:45 +00:00
static char i_flag;
static char F_flag;
static char H_flag;
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;
2024-07-09 19:33:45 +00:00
/* Add new pattern */
2024-07-01 10:23:00 +00:00
regexs[r_size].pattern = str;
2024-07-09 19:33:45 +00:00
2024-07-01 10:23:00 +00:00
r_size++;
return 0;
}
int main(int argc, char **argv) {
int opt;
2024-07-09 19:33:45 +00:00
while ((opt = getopt(argc, argv, "e:iFH")) != -1) {
2024-07-01 10:23:00 +00:00
switch (opt) {
case 'e':
if (addpattern(optarg))
return 1;
break;
2024-07-09 19:33:45 +00:00
case 'i':
i_flag = 1;
break;
case 'F':
F_flag = 1;
break;
case 'H':
H_flag = 1;
break;
2024-07-01 10:23:00 +00:00
default:
2024-07-09 19:33:45 +00:00
printf("grep [eiFH] [FILE]\n\t-e PTRN Pattern to match\n\t-i Ignore case\n\t-H Add 'filename:' prefix\n\t-F PATTERN is a literal (not regexp)\n");
2024-07-01 10:23:00 +00:00
return 0;
}
}
argv += optind;
argc -= optind;
if (r_size == 0) {
fprintf(stderr, "grep: no patterns specified\n");
return 1;
}
free(regexs);
return 0;
}