Skip to content

Commit 285299d

Browse files
committed
Lab util: find
1 parent 1d04c10 commit 285299d

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ mkfs/mkfs: mkfs/mkfs.c $K/fs.h $K/param.h
135135
UPROGS=\
136136
$U/_cat\
137137
$U/_echo\
138+
$U/_find\
138139
$U/_forktest\
139140
$U/_grep\
140141
$U/_init\

user/find.c

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#include "kernel/types.h"
2+
#include "kernel/stat.h"
3+
#include "kernel/fs.h"
4+
#include "user/user.h"
5+
6+
void
7+
find(char *path, char *file)
8+
{
9+
char buf[512], *p;
10+
int fd;
11+
struct dirent de;
12+
struct stat st;
13+
14+
if ((fd = open(path, 0)) < 0) {
15+
fprintf(2, "find: cannot find path %s\n", path);
16+
exit(1);
17+
}
18+
19+
if (fstat(fd, &st) < 0) {
20+
fprintf(2, "find: cannot stat %s\n", path);
21+
close(fd);
22+
exit(1);
23+
}
24+
25+
if (st.type != T_DIR) {
26+
fprintf(2, "find: %s is not a directory\n", path);
27+
close(fd);
28+
exit(1);
29+
}
30+
31+
if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
32+
fprintf(2, "find: path too long\n");
33+
close(fd);
34+
exit(1);
35+
}
36+
37+
strcpy(buf, path);
38+
p = buf + strlen(buf);
39+
*p++ = '/';
40+
while (read(fd, &de, sizeof(de)) == sizeof(de)) {
41+
if (de.inum == 0 || !strcmp(de.name, ".") || !strcmp(de.name, ".."))
42+
continue;
43+
memmove(p, de.name, DIRSIZ);
44+
p[DIRSIZ] = 0;
45+
if (stat(buf, &st) < 0) {
46+
fprintf(1, "find: cannot stat %s\n", buf);
47+
continue;
48+
}
49+
if (st.type == T_FILE && !strcmp(de.name, file)) {
50+
fprintf(1, "%s\n", buf);
51+
} else if (st.type == T_DIR) {
52+
find(buf, file);
53+
}
54+
}
55+
close(fd);
56+
}
57+
58+
int
59+
main(int argc, char *argv[])
60+
{
61+
if (argc < 2 || argc > 3) {
62+
fprintf(2, "Usage: find (path) [file]\n");
63+
exit(1);
64+
} else if (argc < 3) {
65+
find(".", argv[1]);
66+
} else {
67+
find(argv[1], argv[2]);
68+
}
69+
70+
exit(0);
71+
}

0 commit comments

Comments
 (0)