readdir 函数本身并不支持递归读取目录,它只能读取指定目录下的文件和子目录。要实现递归目录读取,你需要结合 opendir、readdir 和 closedir 函数,并在遇到子目录时递归调用读取函数。以下是一个使用 C 语言实现的递归目录读取示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void read_directory(const char *path) {
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[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)) {
printf("Directory: %s\n", full_path);
read_directory(full_path); // 递归读取子目录
} else {
printf("File: %s\n", full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <directory_path>\n", argv[0]);
return 1;
}
read_directory(argv[1]);
return 0;
}
这个程序接受一个目录路径作为参数,然后递归地读取该目录及其所有子目录下的文件和目录。注意,这个示例没有处理符号链接和权限问题,实际使用时可能需要根据需求进行相应的处理。