find finished
This commit is contained in:
60
user/find.c
60
user/find.c
@@ -1,12 +1,64 @@
|
||||
#include "kernel/fcntl.h"
|
||||
#include "kernel/fs.h"
|
||||
#include "kernel/stat.h"
|
||||
#include "kernel/types.h"
|
||||
#include "user/user.h"
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc < 3) {
|
||||
printf("Usage: find path pattern\n");
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user