This repository has been archived by the owner on Jun 23, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
find.c
126 lines (108 loc) · 3.12 KB
/
find.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct file {
FILE *fp;
char *name;
struct file *next;
};
struct file *getinput(int, char**);
void find(char *pattern, int number, int except, struct file *p);
/* find: print lines that match pattern from 1st arg */
int main(int argc, char *argv[]) {
int c, except = 0, number = 0;
struct file *p;
while (--argc > 0 && (*++argv)[0] == '-')
while ((c = *++argv[0]))
switch (c) {
case 'x':
except = 1;
break;
case 'n':
number = 1;
break;
default:
printf("find: illegal option %c\n", c);
argc = 0;
break;
}
if (argc < 1)
printf("Usage: find -x -n [FILE]... pattern\n");
else {
p = getinput(argc, argv);
find(argv[argc-1], number, except, p);
}
exit(0);
}
#define MAXLEN 1000
struct file *getfile(char *, struct file *);
struct file *falloc(void);
struct file *getinput(int argc, char *argv[]) {
struct file *head, *p, *aux;
aux = NULL;
if (argc > 1) { /* if we are given filenames */
do {
head = getfile(*argv++, aux);
argc--;
} while (argc > 1 && head == NULL);
aux = head;
while (argc-- > 1)
if ((p = getfile(*argv++, aux)) != NULL)
aux = p;
} else {
if ((head = falloc()) != NULL) {
head->fp = stdin;
head->name = "input";
head->next = NULL;
}
}
return head;
}
/* getfile: with a file name tries to open the file and creates a node with a
* pointer to it and its name. */
struct file *getfile(char *filename, struct file *aux) {
FILE *file;
struct file *p;
p = NULL;
if ((file = fopen(filename, "r")) != NULL) {
if ((p = falloc()) != NULL) {
p->fp = file;
p->name = filename;
p->next = NULL;
if (aux != NULL)
aux->next = p;
}
} else
fprintf(stderr, "error: cannot open file %s\n", filename);
return p;
}
/* falloc: allocates a new struct file node and returns a pointer to it. */
struct file *falloc(void) {
return (struct file *)malloc(sizeof(struct file));
}
/* find: searches the pattern in the list of structures starting from head. */
void find(char *pattern, int number, int except, struct file *p) {
char line[MAXLEN];
long lineno;
int showFilename;
while (p != NULL) {
lineno = 0;
showFilename = 1;
while (fgets(line, MAXLEN, p->fp) != NULL) {
lineno++;
if ((strstr(line, pattern) != NULL) != except) {
if (showFilename) {
printf("%s:\n", p->name);
showFilename = 0;
}
if (number)
printf("%ld: ", lineno);
printf("%s", line);
}
}
if (!showFilename)
printf("\n");
fclose(p->fp);
p = p->next;
}
}