Linux readdir如何控制遍历深度
导读:在Linux中,使用readdir函数遍历目录时,可以通过递归的方式控制遍历深度。以下是一个简单的示例,展示了如何使用readdir函数遍历目录并控制遍历深度: #include <stdio.h> #include <s...
在Linux中,使用readdir函数遍历目录时,可以通过递归的方式控制遍历深度。以下是一个简单的示例,展示了如何使用readdir函数遍历目录并控制遍历深度:
#include <
stdio.h>
#include <
stdlib.h>
#include <
string.h>
#include <
dirent.h>
#include <
sys/stat.h>
void list_directory(const char *path, int depth) {
struct dirent *entry;
DIR *dp = opendir(path);
if (!dp) {
perror("opendir");
return;
}
while ((entry = readdir(dp))) {
if (strcmp(entry->
d_name, ".") == 0 || strcmp(entry->
d_name, "..") == 0) {
continue;
}
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->
d_name);
struct stat st;
if (stat(full_path, &
st) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(st.st_mode)) {
if (depth >
0) {
printf("%*s%s/\n", depth * 2, "", entry->
d_name);
list_directory(full_path, depth - 1);
}
else {
printf("%*s%s\n", depth * 2, "", entry->
d_name);
}
}
else {
printf("%*s%s\n", depth * 2, "", entry->
d_name);
}
}
closedir(dp);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <
directory>
<
depth>
\n", argv[0]);
return 1;
}
const char *path = argv[1];
int depth = atoi(argv[2]);
list_directory(path, depth);
return 0;
}
在这个示例中,list_directory函数接受一个目录路径和一个深度值。它会遍历该目录及其子目录,并根据指定的深度打印文件和目录名。每深入一层,缩进量会增加两个空格。
要编译并运行此程序,请将其保存为list_directory.c,然后执行以下命令:
gcc -o list_directory list_directory.c
./list_directory /path/to/directory 2
将/path/to/directory替换为您要遍历的目录路径,将2替换为您希望控制的遍历深度。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Linux readdir如何控制遍历深度
本文地址: https://pptw.com/jishu/734777.html
