C:遍历目录树中的树节点
我正在构建一个可遍历的目录树 我绘制的这张图将帮助您轻松理解结构: 如何打印当前工作目录(cwd)的子目录(subDir)列表 例如,我将按以下顺序使用shell命令:C:遍历目录树中的树节点,c,list,ls,treenode,C,List,Ls,Treenode,我正在构建一个可遍历的目录树 我绘制的这张图将帮助您轻松理解结构: 如何打印当前工作目录(cwd)的子目录(subDir)列表 例如,我将按以下顺序使用shell命令: mk_directoryName, cd_directoryName, ls 下面是我对方法“cd”的代码尝试,但它似乎停留在根目录中,并打印cwd的所有目录,而不仅仅是子目录: // *checks whether cwd has a subdirectory named arg // *if yes, the funct
mk_directoryName, cd_directoryName, ls
下面是我对方法“cd”的代码尝试,但它似乎停留在根目录中,并打印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;
}
ls打印方法代码尝试:
// 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;
}
}
关于stackoverflow的几个问题/答案是关于读取目录条目的。关键因素是
DIR
opendir()
,readdir()
和closedir()
头文件:dirent.h
。建议阅读这些函数的手册页,并在stackoverflow中搜索这些关键字。有关stackoverflow的几个问题/答案与阅读目录条目有关。关键因素是DIR
opendir()
,readdir()
和closedir()
头文件:dirent.h
。建议阅读这些函数的手册页并搜索这些关键字。