diff --git a/src/grep.c b/src/grep.c index 07329cf..b5444b8 100644 --- a/src/grep.c +++ b/src/grep.c @@ -54,6 +54,7 @@ static int addpattern(const char *str, const size_t size) { } } + char reg_error_flag = 0; struct pattern **bckp = realloc(ptrns, sizeof(struct pattern *) * (ptrns_size + 1)); if (bckp == NULL) goto ADDP_ERROR; @@ -89,25 +90,25 @@ static int addpattern(const char *str, const size_t size) { else if (w_flag) snprintf(reg_str, rs_size + 4, "%s\\<%s%.*s%s\\>%s", (bol) ? "^" : "", (E_flag) ? "(" : "\\(", (int)size - bol - eol, ptrns[ptrns_size]->str + bol, (E_flag) ? ")" : "\\)", (eol) ? "$" : ""); - char flag = 0; - if (regcomp(&ptrns[ptrns_size]->reg, reg_str, reg_flag) < 0) - flag = 1; + if (regcomp(&ptrns[ptrns_size]->reg, reg_str, reg_flag) != 0) + reg_error_flag = 1; ptrns[ptrns_size]->reg_set = 1; if (x_flag || w_flag) free(reg_str); - if (flag) - goto ADDP_ERROR; } + if (reg_error_flag) + goto ADDP_ERROR; + ptrns_size++; return 0; ADDP_ERROR: ptrns_size++; free_patterns(); - fprintf(stderr, "grep: %s\n", strerror(errno)); + fprintf(stderr, "grep: %s\n", (reg_error_flag) ? "bad regex" : strerror(errno)); return 1; } @@ -141,12 +142,21 @@ static int addpattern_file(const char *file) { return ret; } +static char *my_strcasestr(const char *s1, const char *s2) { + size_t len = strlen(s2); + for (; *s1; s1++) + if (!strncasecmp(s1, s2, len)) + return (char *)s1; + + return NULL; +} + static int cmp(const char *str1, const char *str2) { if (x_flag) return !((i_flag) ? strcasecmp : strcmp)(str1, str2); else - return ((i_flag) ? strcasestr : strstr)(str1, str2) != NULL; + return ((i_flag) ? my_strcasestr : strstr)(str1, str2) != NULL; } static int grep(FILE *fp, const char *file) {