#include #include #include #include #include typedef struct { char *pattern; regex_t rgex; } PATTERN; static PATTERN *regexs; static size_t r_size; static char i_flag; static char F_flag; static char H_flag; 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; /* Add new pattern */ regexs[r_size].pattern = str; r_size++; return 0; } int main(int argc, char **argv) { int opt; while ((opt = getopt(argc, argv, "e:iFH")) != -1) { switch (opt) { case 'e': if (addpattern(optarg)) return 1; break; case 'i': i_flag = 1; break; case 'F': F_flag = 1; break; case 'H': H_flag = 1; break; default: 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"); return 0; } } argv += optind; argc -= optind; if (r_size == 0) { fprintf(stderr, "grep: no patterns specified\n"); return 1; } free(regexs); return 0; }