我正在构建一个目录树。
我正在尝试复制外壳"cd"命令以输入目录。
如何tree_node cwd 设为子目录后返回 cwd?
(cwd = 当前工作目录,subDir = 子目录)例如:
cwd = 子目录->树;
返回CWD;(如何返回 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 directory exists
struct list_node *subDir = cwd -> first_child;
while (subDir != NULL) {
if (strcmp(subDir->tree->string_buffer, arg) == 0) {
printf("Entering directory with name %s n", arg);
subDir->tree = cwd;
return cwd;
printf("Directory with name %sentered.n", arg);
}
subDir = subDir->next;
}
printf("Directory does not exist!n");
}
您需要返回 NULL 或任何指向有效树的指针。您可以检查此代码:
struct tree_node *do_cd(struct tree_node *cwd, struct tree_node *root, char *arg) {
// checks if directory exists
struct list_node *subDir = cwd -> first_child;
while (subDir != NULL) {
if (strcmp(subDir->tree->string_buffer, arg) == 0) {
printf("Entering directory with name %s n", arg);
subDir->tree = cwd;
printf("Directory with name %sentered.n", arg);
return cwd;
}
subDir = subDir->next;
}
printf("Directory does not exist!n");
return NULL;
}