在Linux中,readdir
函数用于读取目录中的文件和子目录。如果你想要限制readdir
的读取深度,你需要在递归遍历目录时添加一个计数器来跟踪当前的深度。
以下是一个简单的示例,展示了如何在C语言中使用readdir
函数并限制读取深度:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
void list_directory(const char *path, int depth) {
if (depth < 0) {
return;
}
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
printf("%*s%s\n", depth * 2, "", entry->d_name);
char child_path[PATH_MAX];
snprintf(child_path, sizeof(child_path), "%s/%s", path, entry->d_name);
struct stat statbuf;
if (stat(child_path, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
list_directory(child_path, depth + 1);
}
}
closedir(dir);
}
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
函数接受一个目录路径和一个深度值。它会读取目录中的所有条目,并根据当前深度打印它们。如果遇到子目录,它会递归地调用自身,增加深度值。当深度值小于0时,递归将停止。
要编译并运行此程序,请将其保存为list_directory.c
,然后使用以下命令:
gcc list_directory.c -o list_directory
./list_directory /path/to/directory 2
将/path/to/directory
替换为你想要列出内容的目录,将2
替换为你想要限制的最大深度。