find finished

This commit is contained in:
2025-03-03 16:47:03 +08:00
parent 930df1c35b
commit b362c49120
10 changed files with 123 additions and 4 deletions

View File

@@ -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);
}

View File

@@ -21,12 +21,33 @@ char *strcpy(char *s, const char *t) {
return os;
}
char *strncpy(char *s, const char *t, int n) {
char *os;
os = s;
if (n <= 0)
return os;
while (--n > 0 && (*s++ = *t++) != 0)
;
while (n-- > 0)
*s++ = 0;
return os;
}
int strcmp(const char *p, const char *q) {
while (*p && *p == *q)
p++, q++;
return (uchar)*p - (uchar)*q;
}
int strncmp(const char *p, const char *q, int n) {
while (n > 0 && *p && *p == *q)
p++, q++, n--;
if (n == 0)
return 0;
return (uchar)*p - (uchar)*q;
}
uint strlen(const char *s) {
int n;

View File

@@ -27,9 +27,11 @@ int uptime(void);
// ulib.c
int stat(const char *, struct stat *);
char *strcpy(char *, const char *);
char *strncpy(char *, const char *, int);
void *memmove(void *, const void *, int);
char *strchr(const char *, char c);
int strcmp(const char *, const char *);
int strncmp(const char *, const char *, int);
void fprintf(int, const char *, ...);
void printf(const char *, ...);
char *gets(char *, int max);