opendir
函数用于打开一个目录流,但它本身并不支持递归遍历。要实现递归目录遍历,你需要结合 readdir
、closedir
和 opendir
函数,并在遇到子目录时递归调用遍历函数。以下是一个使用 C 语言实现的递归目录遍历示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void list_directory_contents(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat path_stat;
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 (stat(full_path, &path_stat) == -1) {
perror("stat");
continue;
}
// 如果是目录,则递归遍历
if (S_ISDIR(path_stat.st_mode)) {
list_directory_contents(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;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
这个程序接受一个命令行参数,即要遍历的目录路径。它会打印出该目录下的所有文件和子目录。注意,这个程序没有处理符号链接,如果目录中包含符号链接,可能会导致无限递归。要处理符号链接,你需要使用 lstat
函数代替 stat
函数,并检查返回的 st_mode
是否表示一个符号链接。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: Node.js日志如何与数据库集成