FIND.C
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
#include "kernel/fs.h"
#define PATH_MAX 512
char *path_append(char *dest, char *src) {
char *ptr =
dest +
strlen(dest); // ptr 需要是一个指针
// 这样获得了dest最后元素也就是结束符'\0'的位置
// 如果使用数组访问dest[strlen(dest)]获得的是结束符元素
while (*src != '\0') {
//"\0"是一个 字符串常量 后跟一个隐式的结束符 \0
// 而'\0'是字符常量 是 C 字符串的结束标志
*(ptr++) = *(src++);
/*
*ptr =*src
src++;
ptr++;
*/
}
*ptr = '\0'; //增加结束符
return dest;
}
void find_file(char *path, char *filename_) {
int fd;
char buf[PATH_MAX];
struct dirent de;
struct stat st;
// open file by only read mode and get fd
if ((fd = open(path, 0)) < 0) {
fprintf(2, "dir_name=%s Wrong\n", path);
exit(1);
}
if (fstat(fd, &st) < 0) {
fprintf(2, "dir_name=%s Wrong\n", path);
close(fd); // get fd before
exit(1);
}
while ((read(fd, &de, sizeof(de)) == sizeof(de))) {
if (de.inum == 0) {
// empty dir
continue;
}
if (strcmp(de.name, ".") == 0 || strcmp(de.name, "..") == 0) {
// skip the dir now and father of dir now
continue;
}
if (strlen(de.name) + strlen(path) + 2 > PATH_MAX) {
//拼接之后的是path/de.name+"\0" 一共len1+len2=2
fprintf(2, "Path too long\n");
continue;
}
strcpy(buf, path);
if (path[strlen(path) - 1] != '/') {
path_append(buf, "/");
}
path_append(buf, de.name);
// check new path
if (stat(buf, &st) < 0) {
fprintf(2, "Path not available\n");
continue;
}
// begin to match filename_
if (st.type == T_FILE) {
if (strcmp(de.name, filename_) == 0) {
printf("%s\n", buf);
}
} else if (st.type == T_DIR) {
find_file(buf, filename_);
}
}
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(2, "Usage: find <path> <filename>\n");
exit(1);
}
find_file(argv[1], argv[2]);
exit(0);
}