#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAXLINE 1000
struct flags {
unsigned int except : 1;
unsigned int number : 1;
} flags;
void fpat(FILE *fp, char *fname, char *pattern, struct flags flags);
int main(int argc, char *argv[])
{
FILE *fp;
char pattern[MAXLINE];
while (--argc > 0 && **++argv == '-') {
while (*++*argv) {
switch (**argv) {
case 'x':
flags.except = true;
break;
case 'n':
flags.number = true;
break;
default:
fprintf(stderr, "find: %c: unknown flag\n", **argv);
exit(1);
break;
}
}
}
if (argc >= 1) {
strncpy(pattern, *argv, MAXLINE);
} else {
fprintf(stderr, "Usage: find -xn pattern [file ...]\n");
exit(1);
}
if (argc == 1) {
fpat(stdin, "", pattern, flags);
fp = stdin;
} else {
while (--argc > 0) {
if (!(fp = fopen(*++argv, "r"))) {
fprintf(stderr, "find: can't open %s\n", *argv);
exit (1);
} else {
fpat(fp, *argv, pattern, flags);
fclose(fp);
}
}
}
return 0;
}
void fpat(FILE *fp, char *fname, char *pattern, struct flags flags)
{
char line[MAXLINE];
unsigned long lineno;
lineno = 0;
while (fgets(line, MAXLINE, fp) != NULL) {
if (!!(strstr(line, pattern)) != flags.except) {
if (*fname)
printf("%s - ", fname);
if (flags.number)
printf("%5lu: ", ++lineno);
printf("%s", line);
}
}
}