Files
xv6-labs/user/find.c
2025-03-03 16:47:03 +08:00

64 lines
1.3 KiB
C

#include "kernel/fs.h"
#include "kernel/stat.h"
#include "kernel/types.h"
#include "user/user.h"
void find(char *path, char *filename) {
int fd = open(path, 0);
char buf[512], *p;
struct dirent de;
struct stat st;
if (fd < 0 || strlen(path) + 1 + DIRSIZ + 1 >= sizeof(buf)) {
fprintf(2, "find: Invalid path: %s\n", path);
// close(fd);
return;
}
if (fstat(fd, &st) < 0) {
fprintf(2, "find: Failed to stat %s\n", path);
close(fd);
return;
}
if (st.type != T_DIR) {
fprintf(2, "find: %s is not a directory\n", path);
close(fd);
return;
}
strncpy(buf, path, strlen(path) + 1);
p = buf + strlen(path);
*p++ = '/';
while (read(fd, &de, sizeof(de)) == sizeof(de)) {
if (de.inum == 0)
continue;
if (!strcmp(de.name, ".") || !strcmp(de.name, ".."))
continue;
memmove(p, de.name, DIRSIZ);
p[DIRSIZ] = 0;
if (stat(buf, &st) < 0) {
fprintf(2, "find: Failed to stat %s\n", buf);
continue;
}
if (st.type == T_DIR) {
find(buf, filename);
} else if (st.type == T_FILE) {
if (!strcmp(filename, "*") || !strcmp(filename, de.name)) {
printf("%s\n", buf);
}
}
}
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: find path filename\n");
exit(1);
}
find(argv[1], argv[2]);
exit(0);
}