home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 22 gnu / 22-gnu.zip / gnugrep.zip / grep.c < prev    next >
C/C++ Source or Header  |  1994-05-20  |  20KB  |  861 lines

  1. /* grep.c - main driver file for grep.
  2.    Copyright (C) 1992 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.  
  18.    Written July 1992 by Mike Haertel.  */
  19.  
  20. #include <errno.h>
  21. #include <stdio.h>
  22.  
  23. #ifndef errno
  24. extern int errno;
  25. #endif
  26.  
  27. #ifdef STDC_HEADERS
  28. #include <stdlib.h>
  29. #else
  30. #include <sys/types.h>
  31. extern char *malloc(), *realloc();
  32. extern void free();
  33. #endif
  34.  
  35. #if defined(STDC_HEADERS) || defined(HAVE_STRING_H)
  36. #include <string.h>
  37. #ifdef NEED_MEMORY_H
  38. #include <memory.h>
  39. #endif
  40. #else
  41. #include <strings.h>
  42. #ifdef __STDC__
  43. extern void *memchr();
  44. #else
  45. extern char *memchr();
  46. #endif
  47. #define strrchr rindex
  48. #endif
  49.  
  50. #ifdef HAVE_UNISTD_H
  51. #include <sys/types.h>
  52. #include <fcntl.h>
  53. #include <unistd.h>
  54. #else
  55. #define O_RDONLY 0
  56. extern int open(), read(), close();
  57. #endif
  58.  
  59. #include "getpagesize.h"
  60. #include "grep.h"
  61.  
  62. #undef MAX
  63. #define MAX(A,B) ((A) > (B) ? (A) : (B))
  64.  
  65. /* Provide missing ANSI features if necessary. */
  66.  
  67. #ifndef HAVE_STRERROR
  68. extern int sys_nerr;
  69. extern char *sys_errlist[];
  70. #define strerror(E) ((E) < sys_nerr ? sys_errlist[(E)] : "bogus error number")
  71. #endif
  72.  
  73. #ifndef HAVE_MEMCHR
  74. #ifdef __STDC__
  75. #define VOID void
  76. #else
  77. #define VOID char
  78. #endif
  79. VOID *
  80. memchr(vp, c, n)
  81.      VOID *vp;
  82.      int c;
  83.      size_t n;
  84. {
  85.   unsigned char *p;
  86.  
  87.   for (p = (unsigned char *) vp; n--; ++p)
  88.     if (*p == c)
  89.       return (VOID *) p;
  90.   return 0;
  91. }
  92. #endif
  93.     
  94. /* Define flags declared in grep.h. */
  95. char *matcher;
  96. int match_icase;
  97. int match_words;
  98. int match_lines;
  99.  
  100. /* Functions we'll use to search. */
  101. static void (*compile)();
  102. static char *(*execute)();
  103.  
  104. /* For error messages. */
  105. static char *prog;
  106. static char *filename;
  107. static int errseen;
  108.  
  109. /* Print a message and possibly an error string.  Remember
  110.    that something awful happened. */
  111. static void
  112. error(mesg, errnum)
  113. #ifdef __STDC__
  114.      const
  115. #endif
  116.      char *mesg;
  117.      int errnum;
  118. {
  119.   if (errnum)
  120.     fprintf(stderr, "%s: %s: %s\n", prog, mesg, strerror(errnum));
  121.   else
  122.     fprintf(stderr, "%s: %s\n", prog, mesg);
  123.   errseen = 1;
  124. }
  125.  
  126. /* Like error(), but die horribly after printing. */
  127. void
  128. fatal(mesg, errnum)
  129. #ifdef __STDC__
  130.      const
  131. #endif
  132.      char *mesg;
  133.      int errnum;
  134. {
  135.   error(mesg, errnum);
  136.   exit(2);
  137. }
  138.  
  139. /* Interface to handle errors and fix library lossage. */
  140. char *
  141. xmalloc(size)
  142.      size_t size;
  143. {
  144.   char *result;
  145.  
  146.   result = malloc(size);
  147.   if (size && !result)
  148.     fatal("memory exhausted", 0);
  149.   return result;
  150. }
  151.  
  152. /* Interface to handle errors and fix some library lossage. */
  153. char *
  154. xrealloc(ptr, size)
  155.      char *ptr;
  156.      size_t size;
  157. {
  158.   char *result;
  159.  
  160.   if (ptr)
  161.     result = realloc(ptr, size);
  162.   else
  163.     result = malloc(size);
  164.   if (size && !result)
  165.     fatal("memory exhausted", 0);
  166.   return result;
  167. }
  168.  
  169. #if !defined(HAVE_VALLOC)
  170. #define valloc malloc
  171. #else
  172. #ifdef __STDC__
  173. extern void *valloc(size_t);
  174. #else
  175. extern char *valloc();
  176. #endif
  177. #endif
  178.  
  179. /* Hairy buffering mechanism for grep.  The intent is to keep
  180.    all reads aligned on a page boundary and multiples of the
  181.    page size. */
  182.  
  183. static char *buffer;        /* Base of buffer. */
  184. static size_t bufsalloc;    /* Allocated size of buffer save region. */
  185. static size_t bufalloc;        /* Total buffer size. */
  186. static int bufdesc;        /* File descriptor. */
  187. static char *bufbeg;        /* Beginning of user-visible stuff. */
  188. static char *buflim;        /* Limit of user-visible stuff. */
  189.  
  190. #if defined(HAVE_WORKING_MMAP)
  191. #include <sys/types.h>
  192. #include <sys/stat.h>
  193. #include <sys/mman.h>
  194.  
  195. static int bufmapped;        /* True for ordinary files. */
  196. static struct stat bufstat;    /* From fstat(). */
  197. static off_t bufoffset;        /* What read() normally remembers. */
  198. #endif
  199.  
  200. /* Reset the buffer for a new file.  Initialize
  201.    on the first time through. */
  202. void
  203. reset(fd)
  204.      int fd;
  205. {
  206.   static int initialized;
  207.  
  208.   if (!initialized)
  209.     {
  210.       initialized = 1;
  211. #ifndef BUFSALLOC
  212.       bufsalloc = MAX(8192, getpagesize());
  213. #else
  214.       bufsalloc = BUFSALLOC;
  215. #endif
  216.       bufalloc = 5 * bufsalloc;
  217.       /* The 1 byte of overflow is a kludge for dfaexec(), which
  218.      inserts a sentinel newline at the end of the buffer
  219.      being searched.  There's gotta be a better way... */
  220.       buffer = valloc(bufalloc + 1);
  221.       if (!buffer)
  222.     fatal("memory exhausted", 0);
  223.       bufbeg = buffer;
  224.       buflim = buffer;
  225.     }
  226.   bufdesc = fd;
  227. #if defined(HAVE_WORKING_MMAP)
  228.   if (fstat(fd, &bufstat) < 0 || !S_ISREG(bufstat.st_mode))
  229.     bufmapped = 0;
  230.   else
  231.     {
  232.       bufmapped = 1;
  233.       bufoffset = lseek(fd, 0, 1);
  234.     }
  235. #endif
  236. }
  237.  
  238. /* Read new stuff into the buffer, saving the specified
  239.    amount of old stuff.  When we're done, 'bufbeg' points
  240.    to the beginning of the buffer contents, and 'buflim'
  241.    points just after the end.  Return count of new stuff. */
  242. static int
  243. fillbuf(save)
  244.      size_t save;
  245. {
  246.   char *nbuffer, *dp, *sp;
  247.   int cc;
  248. #if defined(HAVE_WORKING_MMAP)
  249.   caddr_t maddr;
  250. #endif
  251.   static int pagesize;
  252.  
  253.   if (pagesize == 0 && (pagesize = getpagesize()) == 0)
  254.     abort();
  255.  
  256.   if (save > bufsalloc)
  257.     {
  258.       while (save > bufsalloc)
  259.     bufsalloc *= 2;
  260.       bufalloc = 5 * bufsalloc;
  261.       nbuffer = valloc(bufalloc + 1);
  262.       if (!nbuffer)
  263.     fatal("memory exhausted", 0);
  264.     }
  265.   else
  266.     nbuffer = buffer;
  267.  
  268.   sp = buflim - save;
  269.   dp = nbuffer + bufsalloc - save;
  270.   bufbeg = dp;
  271.   while (save--)
  272.     *dp++ = *sp++;
  273.  
  274.   /* We may have allocated a new, larger buffer.  Since
  275.      there is no portable vfree(), we just have to forget
  276.      about the old one.  Sorry. */
  277.   buffer = nbuffer;
  278.  
  279. #if defined(HAVE_WORKING_MMAP)
  280.   if (bufmapped && bufoffset % pagesize == 0
  281.       && bufstat.st_size - bufoffset >= bufalloc - bufsalloc)
  282.     {
  283.       maddr = buffer + bufsalloc;
  284.       maddr = mmap(maddr, bufalloc - bufsalloc, PROT_READ | PROT_WRITE,
  285.            MAP_PRIVATE | MAP_FIXED, bufdesc, bufoffset);
  286.       if (maddr == (caddr_t) -1)
  287.     {
  288.       fprintf(stderr, "%s: warning: %s: %s\n", filename,
  289.           strerror(errno));
  290.       goto tryread;
  291.     }
  292. #if 0
  293.       /* You might thing this (or MADV_WILLNEED) would help,
  294.      but it doesn't, at least not on a Sun running 4.1.
  295.      In fact, it actually slows us down about 30%! */
  296.       madvise(maddr, bufalloc - bufsalloc, MADV_SEQUENTIAL);
  297. #endif
  298.       cc = bufalloc - bufsalloc;
  299.       bufoffset += cc;
  300.     }
  301.   else
  302.     {
  303.     tryread:
  304.       /* We come here when we're not going to use mmap() any more.
  305.      Note that we need to synchronize the file offset the
  306.      first time through. */
  307.       if (bufmapped)
  308.     {
  309.       bufmapped = 0;
  310.       lseek(bufdesc, bufoffset, 0);
  311.     }
  312.       cc = read(bufdesc, buffer + bufsalloc, bufalloc - bufsalloc);
  313.     }
  314. #else
  315.   cc = read(bufdesc, buffer + bufsalloc, bufalloc - bufsalloc);
  316. #endif
  317.   if (cc > 0)
  318.     buflim = buffer + bufsalloc + cc;
  319.   else
  320.     buflim = buffer + bufsalloc;
  321.   return cc;
  322. }
  323.  
  324. /* Flags controlling the style of output. */
  325. static int out_quiet;        /* Suppress all normal output. */
  326. static int out_invert;        /* Print nonmatching stuff. */
  327. static int out_file;        /* Print filenames. */
  328. static int out_line;        /* Print line numbers. */
  329. static int out_byte;        /* Print byte offsets. */
  330. static int out_before;        /* Lines of leading context. */
  331. static int out_after;        /* Lines of trailing context. */
  332.  
  333. /* Internal variables to keep track of byte count, context, etc. */
  334. static size_t totalcc;        /* Total character count before bufbeg. */
  335. static char *lastnl;        /* Pointer after last newline counted. */
  336. static char *lastout;        /* Pointer after last character output;
  337.                    NULL if no character has been output
  338.                    or if it's conceptually before bufbeg. */
  339. static size_t totalnl;        /* Total newline count before lastnl. */
  340. static int pending;        /* Pending lines of output. */
  341.  
  342. static void
  343. nlscan(lim)
  344.      char *lim;
  345. {
  346.   char *beg;
  347.  
  348.   for (beg = lastnl; beg < lim; ++beg)
  349.     if (*beg == '\n')
  350.       ++totalnl;
  351.   lastnl = beg;
  352. }
  353.  
  354. static void
  355. prline(beg, lim, sep)
  356.      char *beg;
  357.      char *lim;
  358.      char sep;
  359. {
  360.   if (out_file)
  361.     printf("%s%c", filename, sep);
  362.   if (out_line)
  363.     {
  364.       nlscan(beg);
  365.       printf("%d%c", ++totalnl, sep);
  366.       lastnl = lim;
  367.     }
  368.   if (out_byte)
  369.     printf("%lu%c", totalcc + (beg - bufbeg), sep);
  370.   fwrite(beg, 1, lim - beg, stdout);
  371.   fflush(stdout);
  372.   if (ferror(stdout))
  373.     error("writing output", errno);
  374.   lastout = lim;
  375. }
  376.  
  377. /* Print pending lines of trailing context prior to LIM. */
  378. static void
  379. prpending(lim)
  380.      char *lim;
  381. {
  382.   char *nl;
  383.  
  384.   if (!lastout)
  385.     lastout = bufbeg;
  386.   while (pending > 0 && lastout < lim)
  387.     {
  388.       --pending;
  389.       if ((nl = memchr(lastout, '\n', lim - lastout)) != 0)
  390.     ++nl;
  391.       else
  392.     nl = lim;
  393.       prline(lastout, nl, '-');
  394.     }
  395. }
  396.  
  397. /* Print the lines between BEG and LIM.  Deal with context crap.
  398.    If NLINESP is non-null, store a count of lines between BEG and LIM. */
  399. static void
  400. prtext(beg, lim, nlinesp)
  401.      char *beg;
  402.      char *lim;
  403.      int *nlinesp;
  404. {
  405.   static int used;        /* avoid printing "--" before any output */
  406.   char *bp, *p, *nl;
  407.   int i, n;
  408.  
  409.   if (!out_quiet && pending > 0)
  410.     prpending(beg);
  411.  
  412.   p = beg;
  413.  
  414.   if (!out_quiet)
  415.     {
  416.       /* Deal with leading context crap. */
  417.  
  418.       bp = lastout ? lastout : bufbeg;
  419.       for (i = 0; i < out_before; ++i)
  420.     if (p > bp)
  421.       do
  422.         --p;
  423.       while (p > bp && p[-1] != '\n');
  424.  
  425.       /* We only print the "--" separator if our output is
  426.      discontiguous from the last output in the file. */
  427.       if ((out_before || out_after) && used && p != lastout)
  428.     puts("--");
  429.  
  430.       while (p < beg)
  431.     {
  432.       nl = memchr(p, '\n', beg - p);
  433.       prline(p, nl + 1, '-');
  434.       p = nl + 1;
  435.     }
  436.     }
  437.  
  438.   if (nlinesp)
  439.     {
  440.       /* Caller wants a line count. */
  441.       for (n = 0; p < lim; ++n)
  442.     {
  443.       if ((nl = memchr(p, '\n', lim - p)) != 0)
  444.         ++nl;
  445.       else
  446.         nl = lim;
  447.       if (!out_quiet)
  448.         prline(p, nl, ':');
  449.       p = nl;
  450.     }
  451.       *nlinesp = n;
  452.     }
  453.   else
  454.     if (!out_quiet)
  455.       prline(beg, lim, ':');
  456.  
  457.   pending = out_after;
  458.   used = 1;
  459. }
  460.  
  461. /* Scan the specified portion of the buffer, matching lines (or
  462.    between matching lines if OUT_INVERT is true).  Return a count of
  463.    lines printed. */
  464. static int
  465. grepbuf(beg, lim)
  466.      char *beg;
  467.      char *lim;
  468. {
  469.   int nlines, n;
  470.   register char *p, *b;
  471.   char *endp;
  472.  
  473.   nlines = 0;
  474.   p = beg;
  475.   while ((b = (*execute)(p, lim - p, &endp)) != 0)
  476.     {
  477.       /* Avoid matching the empty line at the end of the buffer. */
  478.       if (b == lim && ((b > beg && b[-1] == '\n') || b == beg))
  479.     break;
  480.       if (!out_invert)
  481.     {
  482.       prtext(b, endp, (int *) 0);
  483.       nlines += 1;
  484.     }
  485.       else if (p < b)
  486.     {
  487.       prtext(p, b, &n);
  488.       nlines += n;
  489.     }
  490.       p = endp;
  491.     }
  492.   if (out_invert && p < lim)
  493.     {
  494.       prtext(p, lim, &n);
  495.       nlines += n;
  496.     }
  497.   return nlines;
  498. }
  499.  
  500. /* Search a given file.  Return a count of lines printed. */
  501. static int
  502. grep(fd)
  503.      int fd;
  504. {
  505.   int nlines, i;
  506.   size_t residue, save;
  507.   char *beg, *lim;
  508.  
  509.   reset(fd);
  510.  
  511.   totalcc = 0;
  512.   lastout = 0;
  513.   totalnl = 0;
  514.   pending = 0;
  515.  
  516.   nlines = 0;
  517.   residue = 0;
  518.   save = 0;
  519.  
  520.   for (;;)
  521.     {
  522.       if (fillbuf(save) < 0)
  523.     {
  524.       error(filename, errno);
  525.       return nlines;
  526.     }
  527.       lastnl = bufbeg;
  528.       if (lastout)
  529.     lastout = bufbeg;
  530.       if (buflim - bufbeg == save)
  531.     break;
  532.       beg = bufbeg + save - residue;
  533.       for (lim = buflim; lim > beg && lim[-1] != '\n'; --lim)
  534.     ;
  535.       residue = buflim - lim;
  536.       if (beg < lim)
  537.     {
  538.       nlines += grepbuf(beg, lim);
  539.       if (pending)
  540.         prpending(lim);
  541.     }
  542.       i = 0;
  543.       beg = lim;
  544.       while (i < out_before && beg > bufbeg && beg != lastout)
  545.     {
  546.       ++i;
  547.       do
  548.         --beg;
  549.       while (beg > bufbeg && beg[-1] != '\n');
  550.     }
  551.       if (beg != lastout)
  552.     lastout = 0;
  553.       save = residue + lim - beg;
  554.       totalcc += buflim - bufbeg - save;
  555.       if (out_line)
  556.     nlscan(beg);
  557.     }
  558.   if (residue)
  559.     {
  560.       nlines += grepbuf(bufbeg + save - residue, buflim);
  561.       if (pending)
  562.     prpending(buflim);
  563.     }
  564.   return nlines;
  565. }
  566.  
  567. static char version[] = "GNU grep version 2.0";
  568.  
  569. #define USAGE \
  570.   "Usage: %s [-[[AB] ]<num>] [-[CEFGVLbchilnqsvwxy]] [-[ef]] <expr> [<files...>]\n"
  571.  
  572. static void
  573. usage()
  574. {
  575.   printf("\n%s\n\n", version);
  576.   printf(USAGE, prog);
  577.   printf(
  578.   "  -G -E -F  behave like grep, egrep, fgrep\n"
  579.   "  -<num>    print <num> lines of context on each side\n"
  580.   "  -A <num>  print <num> lines of context after every matching line\n"
  581.   "  -B <num>  print <num> lines of context before every matching line\n"
  582.   "  -e <expr> search for <expr>; useful if <expr> begins with -\n"
  583.   "  -f <file> take <expr> from the given <file>\n"
  584.   "  -C        print 2 lines of context on each side of every match\n"
  585.   "  -V        print the version number on stderr\n"
  586.   "  -b        print every match preceded by its byte offset\n"
  587.   "  -c        print a total count of matching lines only\n"
  588.   "  -h        don't display filenames on matches\n"
  589.   "  -i -y     ignore case difference when comparing strings\n"
  590.   "  -l        list files containing matches only\n"
  591.   "  -L        like -l but list files that don't contain matches\n"
  592.   "  -n        print each match preceded by its line number\n"
  593.   "  -q        be quiet\n"
  594.   "  -s        run silently producing no output except error messages\n"
  595.   "  -v        print only lines that contain no matches for the <expr>\n"
  596.   "  -w        print only lines where the match is a complete word\n"
  597.   "  -x        print only lines where the match is a whole line\n");
  598.  
  599.   exit(2);
  600. }
  601.  
  602. /* Go through the matchers vector and look for the specified matcher.
  603.    If we find it, install it in compile and execute, and return 1.  */
  604. int
  605. setmatcher(name)
  606.      char *name;
  607. {
  608.   int i;
  609.  
  610.   for (i = 0; matchers[i].name; ++i)
  611.     if (strcmp(name, matchers[i].name) == 0)
  612.       {
  613.     compile = matchers[i].compile;
  614.     execute = matchers[i].execute;
  615.     return 1;
  616.       }
  617.   return 0;
  618. }  
  619.  
  620. int
  621. main(argc, argv)
  622.      int argc;
  623.      char *argv[];
  624. {
  625.   char *keys;
  626.   size_t keycc, oldcc, keyalloc;
  627.   int keyfound, count_matches, no_filenames, list_files, suppress_errors;
  628.   int opt, cc, desc, count, status;
  629.   FILE *fp;
  630.   extern char *optarg;
  631.   extern int optind;
  632.  
  633. #ifdef __EMX__
  634.   _wildcard(&argc, &argv);
  635.   setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
  636.   if ((prog = strrchr(argv[0], '.')) != NULL && stricmp(prog, ".exe") == 0)
  637.     *prog = 0;
  638.   if ((prog = strrchr(argv[0], '\\')) != NULL)
  639.     *prog = '/';
  640.   strlwr(argv[0]);
  641. #endif
  642.  
  643.   prog = argv[0];
  644.   if (prog && strrchr(prog, '/'))
  645.     prog = strrchr(prog, '/') + 1;
  646.  
  647.   keys = NULL;
  648.   keycc = 0;
  649.   keyfound = 0;
  650.   count_matches = 0;
  651.   no_filenames = 0;
  652.   list_files = 0;
  653.   suppress_errors = 0;
  654.   matcher = NULL;
  655.  
  656.   while ((opt = getopt(argc, argv, "0123456789A:B:CEFGVX:bce:f:hiLlnqsvwxy"))
  657.      != EOF)
  658.     switch (opt)
  659.       {
  660.       case '0':
  661.       case '1':
  662.       case '2':
  663.       case '3':
  664.       case '4':
  665.       case '5':
  666.       case '6':
  667.       case '7':
  668.       case '8':
  669.       case '9':
  670.     out_before = 10 * out_before + opt - '0';
  671.     out_after = 10 * out_after + opt - '0';
  672.     break;
  673.       case 'A':
  674.     out_after = atoi(optarg);
  675.     if (out_after < 0)
  676.       usage();
  677.     break;
  678.       case 'B':
  679.     out_before = atoi(optarg);
  680.     if (out_before < 0)
  681.       usage();
  682.     break;
  683.       case 'C':
  684.     out_before = out_after = 2;
  685.     break;
  686.       case 'E':
  687.     if (matcher && strcmp(matcher, "egrep") != 0)
  688.       fatal("you may specify only one of -E, -F, or -G", 0);
  689.     matcher = "posix-egrep";
  690.     break;
  691.       case 'F':
  692.     if (matcher && strcmp(matcher, "fgrep") != 0)
  693.       fatal("you may specify only one of -E, -F, or -G", 0);;
  694.     matcher = "fgrep";
  695.     break;
  696.       case 'G':
  697.     if (matcher && strcmp(matcher, "grep") != 0)
  698.       fatal("you may specify only one of -E, -F, or -G", 0);
  699.     matcher = "grep";
  700.     break;
  701.       case 'V':
  702.     fprintf(stderr, "%s\n", version);
  703.     break;
  704.       case 'X':
  705.     if (matcher)
  706.       fatal("matcher already specified", 0);
  707.     matcher = optarg;
  708.     break;
  709.       case 'b':
  710.     out_byte = 1;
  711.     break;
  712.       case 'c':
  713.     out_quiet = 1;
  714.     count_matches = 1;
  715.     break;
  716.       case 'e':
  717.     cc = strlen(optarg);
  718.     keys = xrealloc(keys, keycc + cc + 1);
  719.     if (keyfound)
  720.       keys[keycc++] = '\n';
  721.     strcpy(&keys[keycc], optarg);
  722.     keycc += cc;
  723.     keyfound = 1;
  724.     break;
  725.       case 'f':
  726.     fp = strcmp(optarg, "-") != 0 ? fopen(optarg, "r") : stdin;
  727.     if (!fp)
  728.       fatal(optarg, errno);
  729.     for (keyalloc = 1; keyalloc <= keycc; keyalloc *= 2)
  730.       ;
  731.     keys = xrealloc(keys, keyalloc);
  732.     oldcc = keycc;
  733.     if (keyfound)
  734.       keys[keycc++] = '\n';
  735.     while (!feof(fp)
  736.            && (cc = fread(keys + keycc, 1, keyalloc - keycc, fp)) > 0)
  737.       {
  738.         keycc += cc;
  739.         if (keycc == keyalloc)
  740.           keys = xrealloc(keys, keyalloc *= 2);
  741.       }
  742.     if (fp != stdin)
  743.       fclose(fp);
  744.     /* Nuke the final newline to avoid matching a null string. */
  745.     if (keycc - oldcc > 0 && keys[keycc - 1] == '\n')
  746.       --keycc;
  747.     keyfound = 1;
  748.     break;
  749.       case 'h':
  750.     no_filenames = 1;
  751.     break;
  752.       case 'i':
  753.       case 'y':            /* For old-timers . . . */
  754.     match_icase = 1;
  755.     break;
  756.       case 'L':
  757.     /* Like -l, except list files that don't contain matches.
  758.        Inspired by the same option in Hume's gre. */
  759.     out_quiet = 1;
  760.     list_files = -1;
  761.     break;
  762.       case 'l':
  763.     out_quiet = 1;
  764.     list_files = 1;
  765.     break;
  766.       case 'n':
  767.     out_line = 1;
  768.     break;
  769.       case 'q':
  770.     out_quiet = 1;
  771.     break;
  772.       case 's':
  773.     suppress_errors = 1;
  774.     break;
  775.       case 'v':
  776.     out_invert = 1;
  777.     break;
  778.       case 'w':
  779.     match_words = 1;
  780.     break;
  781.       case 'x':
  782.     match_lines = 1;
  783.     break;
  784.       default:
  785.     usage();
  786.     break;
  787.       }
  788.  
  789.   if (!keyfound)
  790.     if (optind < argc)
  791.       {
  792.     keys = argv[optind++];
  793.     keycc = strlen(keys);
  794.       }
  795.     else
  796.       usage();
  797.  
  798.   if (!matcher)
  799.     matcher = prog;
  800.  
  801.   if (!setmatcher(matcher) && !setmatcher("default"))
  802.     abort();
  803.  
  804.   (*compile)(keys, keycc);
  805.  
  806.   if (argc - optind > 1 && !no_filenames)
  807.     out_file = 1;
  808.  
  809.   status = 1;
  810.  
  811.   if (optind < argc)
  812.     while (optind < argc)
  813.       {
  814.     desc = strcmp(argv[optind], "-") ? open(argv[optind], O_RDONLY) : 0;
  815.     if (desc < 0)
  816.       {
  817.         if (!suppress_errors)
  818.           error(argv[optind], errno);
  819.       }
  820.     else
  821.       {
  822.         filename = desc == 0 ? "(standard input)" : argv[optind];
  823.         count = grep(desc);
  824.         if (count_matches)
  825.           {
  826.         if (out_file)
  827.           printf("%s:", filename);
  828.         printf("%d\n", count);
  829.           }
  830.         if (count)
  831.           {
  832.         status = 0;
  833.         if (list_files == 1)
  834.           printf("%s\n", filename);
  835.           }
  836.         else if (list_files == -1)
  837.           printf("%s\n", filename);
  838.       }
  839.     if (desc != 0)
  840.       close(desc);
  841.     ++optind;
  842.       }
  843.   else
  844.     {
  845.       filename = "(standard input)";
  846.       count = grep(0);
  847.       if (count_matches)
  848.     printf("%d\n", count);
  849.       if (count)
  850.     {
  851.       status = 0;
  852.       if (list_files == 1)
  853.         printf("(standard input)\n");
  854.     }
  855.       else if (list_files == -1)
  856.     printf("(standard input)\n");
  857.     }
  858.  
  859.   exit(errseen ? 2 : status);
  860. }
  861.