home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / magazine / pctchnqs / 1991 / number4 / l2.c < prev    next >
Text File  |  1991-07-20  |  2KB  |  55 lines

  1. /* Program to exercise buffer-search routines in Listings 1 & 3.
  2.    (Must be modified to put copy of pattern as sentinel at end of the
  3.    search buffer in order to be used with Listing 4.) */
  4.  
  5. #include <stdio.h>
  6. #include <string.h>
  7. #include <fcntl.h>
  8.  
  9. #define DISPLAY_LENGTH  40
  10. #define BUFFER_SIZE     0x8000
  11.  
  12. extern unsigned char * FindString(unsigned char *, unsigned int,
  13.       unsigned char *, unsigned int);
  14. void main(void);
  15.  
  16. void main() {
  17.    unsigned char TempBuffer[DISPLAY_LENGTH+1];
  18.    unsigned char Filename[150], Pattern[150], *MatchPtr, *TestBuffer;
  19.    int Handle;
  20.    unsigned int WorkingLength;
  21.  
  22.    printf("File to search:");
  23.    gets(Filename);
  24.    printf("Pattern for which to search:");
  25.    gets(Pattern);
  26.  
  27.    if ( (Handle = open(Filename, O_RDONLY | O_BINARY)) == -1 ) {
  28.       printf("Can't open file: %s\n", Filename); exit(1);
  29.    }
  30.    /* Get memory in which to buffer the data */
  31.    if ( (TestBuffer=(unsigned char *)malloc(BUFFER_SIZE+1)) == NULL) {
  32.       printf("Can't get enough memory\n"); exit(1);
  33.    }
  34.    /* Process a BUFFER_SIZE chunk */
  35.    if ( (int)(WorkingLength =
  36.          read(Handle, TestBuffer, BUFFER_SIZE)) == -1 ) {
  37.       printf("Error reading file %s\n", Filename); exit(1);
  38.    }
  39.    TestBuffer[WorkingLength] = 0; /* 0-terminate buffer for printf */
  40.    /* Search for the pattern and report the results */
  41.    if ((MatchPtr = FindString(TestBuffer, WorkingLength, Pattern,
  42.          (unsigned int) strlen(Pattern))) == NULL) {
  43.       /* Pattern wasn't found */
  44.       printf("\"%s\" not found\n", Pattern);
  45.    } else {
  46.       /* Pattern was found. Zero-terminate TempBuffer; strncpy
  47.          won't do it if DISPLAY_LENGTH characters are copied */
  48.       TempBuffer[DISPLAY_LENGTH] = 0;
  49.       printf("\"%s\" found. Next %d characters at match:\n\"%s\"\n",
  50.             Pattern, DISPLAY_LENGTH,
  51.             strncpy(TempBuffer, MatchPtr, DISPLAY_LENGTH));
  52.    }
  53.    exit(0);
  54. }
  55.