Skip to content

Commit 2e79bd6

Browse files
committed
Change while loop to for loop
1 parent 0f6b503 commit 2e79bd6

File tree

1 file changed

+8
-13
lines changed

1 file changed

+8
-13
lines changed

chapter07/7-7.c

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,13 @@ int fgetLine(FILE *fp, char *line, int max)
4444
int main(int argc, char *argv[])
4545
{
4646
char line[MAXLINE];
47-
long lineno = 0;
47+
long lineno;
4848
int c, except = 0, number = 0, found = 0;
4949
char *prog = argv[0];
5050
char *pattern;
5151
FILE *fp;
5252

53-
while (--argc > 0 && (*++argv)[0] == '-')
53+
while (--argc > 0 && (*++argv)[0] == '-') /* check for flags */
5454
while ((c = *++argv[0]))
5555
switch (c) {
5656
case 'x':
@@ -68,35 +68,30 @@ int main(int argc, char *argv[])
6868

6969
if (argc < 1)
7070
printf("Usage: find -x -n pattern\n");
71-
else if (argc == 1)
72-
while (getLine(line, MAXLINE) > 0) {
73-
lineno++;
71+
else if (argc == 1) { /* input from stdin */
72+
for (lineno = 1; getLine(line, MAXLINE) > 0; lineno++)
7473
if ((strstr(line, *argv) != NULL) != except) {
7574
if (number)
7675
printf ("%ld:", lineno);
7776
printf("%s", line);
7877
found++;
7978
}
80-
}
81-
else {
82-
pattern = *argv; /* save a point to the pattern */
79+
} else { /* input from file or set of files */
80+
pattern = *argv; /* save a pointer to the pattern */
8381
while (argc-- > 1) {
8482
if ((fp = fopen(*++argv, "r")) == NULL) {
8583
fprintf(stderr, "%s: can't open %s\n", prog, *argv);
8684
exit(EXIT_FAILURE);
87-
}
88-
lineno = 0;
85+
}
8986
while (!feof(fp))
90-
while (fgetLine(fp, line, MAXLINE) > 0) {
91-
lineno++;
87+
for (lineno = 1; fgetLine(fp, line, MAXLINE) > 0; lineno++)
9288
if ((strstr(line, pattern) != NULL) != except) {
9389
printf("%s:", *argv); /* print file name */
9490
if (number)
9591
printf ("%ld:", lineno);
9692
printf("%s", line);
9793
found++;
9894
}
99-
}
10095
fclose(fp);
10196
}
10297
}

0 commit comments

Comments
 (0)