在Ubuntu中,使用readdir
函数读取目录时,可以通过递归遍历目录并检查当前深度来限制读取深度。以下是一个简单的C语言示例,展示了如何使用readdir
函数限制读取深度:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void read_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;
}
char full_path[1024];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
struct stat statbuf;
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
printf("Directory: %s\n", full_path);
read_directory(full_path, depth - 1);
} else {
printf("File: %s\n", full_path);
}
}
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]);
read_directory(path, depth);
return 0;
}
在这个示例中,read_directory
函数接受两个参数:要读取的目录路径和最大深度。它会递归地遍历目录,并在达到最大深度时停止递归。
编译并运行此程序:
gcc -o read_directory_example read_directory_example.c
./read_directory_example /path/to/directory 2
将/path/to/directory
替换为要读取的目录路径,将2
替换为所需的最大深度。