温馨提示×

readdir如何实现递归读取

小樊
47
2025-07-10 10:46:53
栏目: 编程语言

readdir 函数本身并不支持递归读取目录,它只能读取指定目录下的文件和子目录。要实现递归读取,你需要结合其他函数(如 opendirclosedirreaddir)来编写递归函数。以下是一个使用 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; } snprintf(path_stat.path, sizeof(path_stat.path), "%s/%s", path, entry->d_name); if (stat(path_stat.path, &path_stat) == -1) { perror("stat"); continue; } if (S_ISDIR(path_stat.st_mode)) { printf("Directory: %s\n", path_stat.path); list_directory_contents(path_stat.path); } else { printf("File: %s\n", path_stat.path); } } closedir(dir); } int main(int argc, char *argv[]) { if (argc < 2) { printf("Usage: %s <directory_path>\n", argv[0]); return 1; } list_directory_contents(argv[1]); return 0; } 

这个程序接受一个目录路径作为命令行参数,并递归地列出该目录下的所有文件和子目录。请注意,这个示例仅适用于类 Unix 系统(如 Linux 和 macOS),因为它使用了 POSIX 标准库函数。如果你使用的是 Windows 系统,你需要使用 Windows API 函数(如 FindFirstFileFindNextFileFindClose)来实现类似的功能。

0