readdir
函数本身并不支持递归读取目录,它只能读取指定目录下的文件和子目录。要实现递归读取目录,你需要结合其他函数,如 opendir
、readdir
和 closedir
,并在遍历过程中检查每个条目是否为目录,如果是目录,则递归调用读取函数。
以下是一个使用 C 语言实现的递归读取目录的示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void read_directory_recursive(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
if (!(dir = opendir(path))) {
perror("opendir");
return;
}
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);
if (lstat(full_path, &statbuf) == -1) {
perror("lstat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
printf("Directory: %s\n", full_path);
read_directory_recursive(full_path);
} else {
printf("File: %s\n", full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
read_directory_recursive(argv[1]);
return EXIT_SUCCESS;
}
这个程序接受一个目录路径作为命令行参数,并递归地读取该目录及其子目录下的所有文件和目录。注意,这个示例使用了 lstat
函数而不是 stat
函数,以避免在处理符号链接时出现问题。