dcn@ihuxl.UUCP (Dave Newkirk) (11/14/83)
/* fgrep - fast pattern matcher */ #include "stdio.h" int numbering, except, files ; char *fname ; main(argc, argv) int argc ; char *argv[] ; { char *s, *pattern ; FILE *input ; numbering = except = files = FALSE ; while( --argc>0 && **++argv == '-' ) for( s=&argv[0][1] ; *s != EOS ; s++ ) switch( *s ) { case 'n': numbering = TRUE ; break ; case 'x': except = TRUE ; break ; default: fprintf(stderr, "fgrep: unknown option %c\n", *s ) ; argc = -1 ; break ; } if( argc <= 0 ) { fprintf(stderr, "usage: fgrep [-nx] pattern [files]\n"); exit(1) ; } pattern = *argv ; argc-- ; argv++ ; if( argc > 1 ) files = TRUE ; if( argc == 0 ) fgrep( stdin, pattern ) ; else for( ; argc>0 ; argc--,argv++) if( (input=fopen(*argv,"r")) == NULL ) { fprintf(stderr, "fgrep: can't open %s\n", *argv) ; exit(1) ; } else { fname = *argv ; fgrep(input, pattern) ; fclose( input ) ; } exit(0) ; } /* end main */ /* fgrep - match pattern to file */ fgrep( in, pat ) FILE *in ; char *pat ; { char line[ MAXLINE ], *fgets() ; int lines ; lines = 0 ; while( fgets(line, MAXLINE, in) != NULL ) { lines++ ; if( (match(line, pat) >= 0) != except ) { if( files ) printf("%s: ", fname ) ; if( numbering ) printf("%d: ", lines ) ; printf("%s", line ) ; } } } /* end fgrep */ /* match - return index of pattern */ match( subject, pattern ) char *subject, *pattern ; { char *s, *p, *ss ; for( s=subject ; *s != EOS ; s++ ) { for( ss=s, p=pattern ; *p != EOS && *p == *ss ; p++, ss++ ) ; if( *p == EOS ) return s - subject ; } return -1 ; } /* end match */ /* fgets - read a line from a file. */ char *fgets(line, maxline, input) char *line ; int maxline ; FILE *input ; { int c ; char *start_line ; start_line = line; while( --maxline>0 && (c=agetc(input)) != EOF ) if( (*line++ = c) == NL ) break ; *line = 0 ; if( c == EOF && line == start_line ) return(NULL) ; return(line) ; }