Last active
September 10, 2017 16:35
-
-
Save fallenleavesguy/d9e9c1e7ff9bbb43c611693152941aac to your computer and use it in GitHub Desktop.
simple grep in c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* simple grep in c | |
*/ | |
#include <stdio.h> | |
#define MAXLINE 1000 | |
int getOneLine(char line[], int max); | |
int strindex(char source[], char searchfor[]); | |
char pattern[] = "ould"; | |
int main() { | |
char line[MAXLINE]; | |
int found = 0; | |
while (getOneLine(line, MAXLINE) > 0) | |
if (strindex(line, pattern) >= 0) { | |
printf("%s\n", line); | |
found++; | |
} | |
return found;;; | |
} | |
int getOneLine(char s[], int lim) { | |
int c = 0, i = 0; | |
while(--lim > 0 && (c = getchar()) !=EOF && c != '\n') | |
s[i++] = c; | |
if (c == '\n') | |
s[i++] = c; | |
s[i] = '\0'; | |
return i; | |
} | |
int strindex(char s[], char t[]) { | |
int i, j, k; | |
for (i = 0; s[i] != '\0'; i++) { | |
for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++) | |
; | |
if (k > 0 && t[k] == '\0') | |
return i; | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment