/* $Id: grep.c 729 2008-02-08 23:38:01Z phf $ */ /* Rebecca Shapiro, based on Raluca Musaloiu-E's grep*/ /* cs120 lab 2 */ /* simplified version of grep */ /* Reads from stdin prints to stdout*/ /* usage: grep */ /* reads standard input to find match */ #include #include #define MAXLINE 256 int match(char line[], char pattern[]); int getline(char line[], int length); int main(int argc, char *argv[]) { char line[MAXLINE+1]; /*read command line args, make sure you have enough*/ if (argc !=2){ printf("Usage: grep \n"); exit(EXIT_FAILURE); } /*loop through stdin*/ while(getline(line, MAXLINE) != 0){ /*test if line matches*/ if(match(line,argv[1])){ /*print if line matches*/ printf("%s",line); } } return EXIT_SUCCESS; } /*Reads upto \n or EOF from stdin and places characters (including \n) into line, for up to length characters (including newline) returns the number of characters read (not including EOF or newline) */ int getline(char line[], int length) { int i; char c; /*loop: read in one line at a time*/ i = 0; while(((c =getchar()) != EOF) && (c != '\n') && (i < length)){ line[i++]=c; } line[i] = '\n'; line[i+1] = '\0'; return i; } /*Returns 1 if pattern is a substring of line, 0 otherwise*/ int match(char line[], char pattern[]) { int i, j; for (i = 0; line[i] != '\0'; i++) { for (j = 0; pattern[j] != '\0' && line[i + j] == pattern[j]; j++); if (pattern[j] == '\0') return 1; } return 0; }