aboutsummaryrefslogtreecommitdiff
path: root/7.7/main.c
diff options
context:
space:
mode:
Diffstat (limited to '7.7/main.c')
-rw-r--r--7.7/main.c77
1 files changed, 77 insertions, 0 deletions
diff --git a/7.7/main.c b/7.7/main.c
new file mode 100644
index 0000000..ee944b4
--- /dev/null
+++ b/7.7/main.c
@@ -0,0 +1,77 @@
+#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);
+ }
+ }
+}