Skip to content

Commit 4c7f64e

Browse files
committed
Initial commit
completed exercise. Will work on cleaning up the code a little.
1 parent d2a5015 commit 4c7f64e

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

chapter07/7-7.c

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
/*
2+
* Exercise 7-7. Modify the pattern finding program of Chapter 5 to take its
3+
* input from a set named files or, if no files are named as arguments, from
4+
* the standard input. Should the file name be printed when a matching line is
5+
* found?
6+
* Answer: of course!
7+
*
8+
* By Faisal Saadatmand
9+
*/
10+
11+
#include <stdio.h>
12+
#include <string.h>
13+
#include <stdlib.h>
14+
15+
#define MAXLINE 1000
16+
17+
/* fucntions */
18+
int getLine(char *, int);
19+
20+
/* getLine: get line into s, return length */
21+
int getLine(char *line, int max)
22+
{
23+
int c, i;
24+
25+
i = 0;
26+
while (--max > 0 && (c = getchar()) != EOF && c != '\n')
27+
line[i++] = c;
28+
if (c == '\n')
29+
line[i++] = c;
30+
line[i] = '\0';
31+
return i;
32+
}
33+
34+
/* fgetLine: read line, return length - fgets version */
35+
int fgetLine(FILE *fp, char *line, int max)
36+
{
37+
if (fgets(line, max, fp) == NULL)
38+
return 0;
39+
else
40+
return strlen(line);
41+
}
42+
43+
/* find: print lines that match pattern from 1s arg */
44+
int main(int argc, char *argv[])
45+
{
46+
char line[MAXLINE];
47+
long lineno = 0;
48+
int c, except = 0, number = 0, found = 0;
49+
char *prog = argv[0];
50+
char *pattern;
51+
FILE *fp;
52+
53+
while (--argc > 0 && (*++argv)[0] == '-')
54+
while ((c = *++argv[0]))
55+
switch (c) {
56+
case 'x':
57+
except = 1;
58+
break;
59+
case 'n':
60+
number = 1;
61+
break;
62+
default:
63+
printf("find: illegal option %c\n", c);
64+
argc = 0;
65+
found = -1;
66+
break;
67+
}
68+
69+
if (argc < 1)
70+
printf("Usage: find -x -n pattern\n");
71+
else if (argc == 1)
72+
while (getLine(line, MAXLINE) > 0) {
73+
lineno++;
74+
if ((strstr(line, *argv) != NULL) != except) {
75+
if (number)
76+
printf ("%ld:", lineno);
77+
printf("%s", line);
78+
found++;
79+
}
80+
}
81+
else {
82+
pattern = *argv; /* save a point to the pattern */
83+
while (argc-- > 1) {
84+
if ((fp = fopen(*++argv, "r")) == NULL) {
85+
fprintf(stderr, "%s: can't open %s\n", prog, *argv);
86+
exit(EXIT_FAILURE);
87+
}
88+
lineno = 0;
89+
while (!feof(fp))
90+
while (fgetLine(fp, line, MAXLINE) > 0) {
91+
lineno++;
92+
if ((strstr(line, pattern) != NULL) != except) {
93+
printf("%s:", *argv); /* print file name */
94+
if (number)
95+
printf ("%ld:", lineno);
96+
printf("%s", line);
97+
found++;
98+
}
99+
}
100+
fclose(fp);
101+
}
102+
}
103+
return found;
104+
}

0 commit comments

Comments
 (0)