
/* srch.c */
/* Andrew Davison (ad@ratree.psu.ac.th) */
/* February 11th, 1997 */

/* Usage:
      srch string file
   Search a component file of a large text 'database' 
   (one of a2f.txt, g2l.txt, m2r.txt, s2z.txt).
   The search string and filename are supplied as 
   command line arguments.
*/

#include <stdio.h>
#include <string.h>
#include <time.h>      /* for time() */

#define MAXLEN    130   /* max length of a string */
#define MAXMATCH  10    /* max number of reported matches in the file */


void search_db(char *match_str, char *fnm);


int main(int argc, char *argv[])
{
  time_t t;

  if (argc != 3) {
    fprintf(stderr, "Usage: srch string filename\n");
    exit(1);
  }

  t = time(NULL);
  search_db(argv[1], argv[2]);
  printf("Execution time for %s search: %.0f secs\n",
                      argv[2], difftime(time(NULL), t) );
  return 0;
}


void search_db(char *match_str, char *fnm)
/* Do a linear search over the database fnm. Print
   up to the first MAXMATCH hits and count the rest.
   A hit is a line which contains match_str.
*/
{
  FILE *fp;
  char buf[MAXLEN];
  int count = 0;
  time_t t;

  if ((fp = fopen(fnm, "r")) == NULL)
    fprintf(stderr, "Could not read %s\n", fnm);
  else {
    t = time(NULL);
    while (fgets(buf, MAXLEN, fp) != NULL)
      if (strstr(buf, match_str) != NULL) {
        if (count <= MAXMATCH)
          printf("%2d. %s\n", count, buf);
        count++;
      }
    fclose(fp);
    printf("Time to scan %s: %.0f secs\n", fnm, difftime(time(NULL),t));
    printf("Number of matches = %d\n", count);
  }
}


