exc/k&r/04-funcs-and-prog-struct/04-find/find-book.c

48 lines
1.1 KiB
C

#include <stdio.h>
#define MAXLINE 1000 /* maximum input line length */
int getln(char line[], int lim);
int strindex(char source[], char searchfor[]);
/* find: prints lines containing pattern, returns number of matching lines */
int find(char *pattern, char lineno_flag, char except_flag)
{
char line[MAXLINE];
int found = 0;
long lineno;
for (lineno = 1; getln(line, MAXLINE) > 0; lineno++)
if ((strindex(line, pattern) >= 0) != except_flag) {
if (lineno_flag)
printf("%ld:", lineno);
printf("%s", line);
found++;
}
return found;
}
/* getline: get line (including \n) into s, return length */
int getln(char *s, int lim)
{
int c, i = 0;
while (--lim > 0 && (c = getchar()) != EOF && (s[i++] = c) != '\n')
;
s[i] = '\0';
return i;
}
/* strindex: return index of t in s, -1 if none */
int strindex(char s[], char t[])
{
int i, j, k;
for (i = 0; s[i]; i++) {
for (j=i, k=0; t[k] && s[j] == t[k]; j++, k++)
;
if (k > 0 && !t[k])
return i;
}
return -1;
}