我正在构建一个可遍历的目录树。
我绘制的图表将帮助您轻松理解结构:
如何打印当前工作目录(cwd)的子目录(subDir)列表?
例如,我将按以下顺序使用shell命令:
mk_directoryName, cd_directoryName, ls
下面是我对'cd'方法的代码尝试,但它似乎留在根目录并打印所有DIRECTORIES而不仅仅是cwd的子目录:
// *checks whether cwd has a subdirectory named arg
// *if yes, the function returns the corresponding tree node (and become new working directory)
// *if no, prints an error message
// *handle cd and cd ..
struct tree_node *do_cd(struct tree_node *cwd, struct tree_node *root, char *arg) {
// checks if cwd has a subdirectory named arg
struct list_node *subDir = cwd -> first_child;
struct tree_node *parDir = cwd -> parent;
printf("Making current working directory the parent directory.\n");
while (subDir != NULL) {
if (strcmp(subDir -> tree -> string_buffer, arg) == 0) {
printf("Subdirectory exists: Entering!\n");
cwd = subDir-> tree;
printf("Making subdirectory current working directory: name = %s\n", arg);
printf("Returning current working directory: %s.\n", arg);
return cwd;
}
else if (strcmp(arg, "..") == 0) {
cwd = parDir;
printf("Returning to parent directory.\n");
return cwd;
}
else if (strcmp(arg, "") == 0) {
printf("Returning to root directory.\n");
return root;
}
subDir = subDir-> next;
}
printf("Directory does not exist!\n");
return cwd;
}
打印方法代码尝试:
// prints all children of the directory cwd (not recursively)
void do_ls(struct tree_node *cwd) {
printf("Listing Directories...\n");
struct list_node *subDir = cwd -> first_child;
while (subDir != NULL) {
printf("%s\n", subDir ->tree -> string_buffer);
subDir = subDir->next;
}
}