在Linux中,使用readdir
函數讀取目錄時,可以通過遞歸遍歷目錄并檢查當前目錄深度來限制目錄深度。以下是一個簡單的示例,展示了如何在C語言中使用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) {
if (depth < 0) {
return;
}
DIR *dir = opendir(path);
if (!dir) {
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("%*s%s/\n", depth * 2, "", entry->d_name);
list_directory(full_path, depth - 1);
} else {
printf("%*s%s\n", depth * 2, "", entry->d_name);
}
}
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 -o list_directory list_directory.c
./list_directory /path/to/directory 2
將/path/to/directory
替換為您要列出目錄的路徑,將2
替換為您要限制的最大深度。