#include #include #include #include #include typedef struct { char *pattern; regex_t rgex; } PATTERN; static PATTERN *regexs; static size_t r_size; static int addpattern(char *str) { 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; }