X-Git-Url: https://git.librecmc.org/?a=blobdiff_plain;f=grep.c;h=84bb99667373720d1fcbb0108a89988d691e2ca7;hb=c054b21f7d0420b1f8f8100a17fb14de9c947ef2;hp=44ca028345380fb79776de87a9eddbecf7fb7819;hpb=aa0765e11bdeba5c5abf745369a8430c8311d60c;p=oweals%2Fbusybox.git diff --git a/grep.c b/grep.c index 44ca02834..84bb99667 100644 --- a/grep.c +++ b/grep.c @@ -32,29 +32,55 @@ #include static const char grep_usage[] = -"grep [-ihn]... PATTERN [FILE]...\n" +"grep [OPTIONS]... PATTERN [FILE]...\n\n" "Search for PATTERN in each FILE or standard input.\n\n" +"OPTIONS:\n" "\t-h\tsuppress the prefixing filename on output\n" "\t-i\tignore case distinctions\n" "\t-n\tprint line number with output lines\n\n" #if defined BB_REGEXP -"This version of grep matches full regexps.\n"; +"This version of grep matches full regular expresions.\n"; #else -"This version of grep matches strings (not full regexps).\n"; +"This version of grep matches strings (not regular expresions).\n"; #endif +static void do_grep(FILE *fp, char* needle, char *fileName, int tellName, int ignoreCase, int tellLine) +{ + char *cp; + long line = 0; + char haystack[BUF_SIZE]; + + while (fgets (haystack, sizeof (haystack), fp)) { + line++; + cp = &haystack[strlen (haystack) - 1]; + + if (*cp != '\n') + fprintf (stderr, "%s: Line too long\n", fileName); + + if (find_match(haystack, needle, ignoreCase) == TRUE) { + if (tellName==TRUE) + printf ("%s:", fileName); + + if (tellLine==TRUE) + printf ("%ld:", line); + + fputs (haystack, stdout); + } + } +} + + extern int grep_main (int argc, char **argv) { FILE *fp; - const char *needle; - const char *name; - const char *cp; - int tellName=TRUE; + char *cp; + char *needle; + char *fileName; + int tellName=FALSE; int ignoreCase=FALSE; int tellLine=FALSE; - long line; - char haystack[BUF_SIZE]; + ignoreCase = FALSE; tellLine = FALSE; @@ -76,7 +102,7 @@ extern int grep_main (int argc, char **argv) break; case 'h': - tellName = FALSE; + tellName = TRUE; break; case 'n': @@ -91,39 +117,24 @@ extern int grep_main (int argc, char **argv) needle = *argv++; argc--; - while (argc-- > 0) { - name = *argv++; - - fp = fopen (name, "r"); - if (fp == NULL) { - perror (name); - continue; - } - - line = 0; - - while (fgets (haystack, sizeof (haystack), fp)) { - line++; - cp = &haystack[strlen (haystack) - 1]; + if (argc==0) { + do_grep( stdin, needle, "stdin", FALSE, ignoreCase, tellLine); + } else { + while (argc-- > 0) { + fileName = *argv++; - if (*cp != '\n') - fprintf (stderr, "%s: Line too long\n", name); - - if (find_match(haystack, needle, ignoreCase) == TRUE) { - if (tellName==TRUE) - printf ("%s: ", name); - - if (tellLine==TRUE) - printf ("%ld: ", line); - - fputs (haystack, stdout); + fp = fopen (fileName, "r"); + if (fp == NULL) { + perror (fileName); + continue; } - } - if (ferror (fp)) - perror (name); + do_grep( fp, needle, fileName, tellName, ignoreCase, tellLine); - fclose (fp); + if (ferror (fp)) + perror (fileName); + fclose (fp); + } } exit( TRUE); }