在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
替換為您希望控制的遍歷深度。