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

48 lines
1.1 KiB
C
Raw Normal View History

2023-06-25 14:30:48 +02:00
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line length */
int getln(char line[], int lim);
int strindex(char source[], char searchfor[]);
2023-06-25 14:30:48 +02:00
/* find: prints lines containing pattern, returns number of matching lines */
2023-07-22 16:09:12 +02:00
int find(char *pattern, char lineno_flag, char except_flag)
2023-06-25 14:30:48 +02:00
{
char line[MAXLINE];
int found = 0;
2023-07-22 16:09:12 +02:00
long lineno;
2023-06-25 14:30:48 +02:00
2023-07-22 16:09:12 +02:00
for (lineno = 1; getln(line, MAXLINE) > 0; lineno++)
if ((strindex(line, pattern) >= 0) != except_flag) {
2023-07-22 16:09:12 +02:00
if (lineno_flag)
printf("%ld:", lineno);
2023-06-25 14:30:48 +02:00
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[])
2023-06-25 14:30:48 +02:00
{
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;
}
2023-06-25 14:30:48 +02:00
return -1;
}