readdir
函数本身不会递归地读取子目录。它只能读取指定目录下的文件和子目录。如果你想要递归地读取子目录,你需要自己编写一个递归函数来实现这个功能。
下面是一个简单的示例,展示了如何使用 readdir
函数递归地读取目录及其子目录中的所有文件:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void read_directory_recursive(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
dir = opendir(path);
if (!dir) {
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)) {
read_directory_recursive(full_path);
} else {
printf("%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;
}
这个程序接受一个目录路径作为参数,并递归地读取该目录及其子目录中的所有文件。注意,这个示例程序没有处理符号链接和其他可能的错误情况。在实际应用中,你可能需要根据你的需求进行相应的调整。