温馨提示×

如何用readdir遍历子目录

小樊
44
2025-07-16 13:11:12
栏目: 编程语言

readdir 是一个用于读取目录内容的函数,通常在 C 语言中使用。要使用 readdir 遍历子目录,你需要结合其他函数,如 opendirclosedirstat。以下是一个简单的示例,展示了如何使用这些函数遍历子目录:

#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 == NULL) { perror("opendir"); return; } while ((entry = readdir(dir)) != NULL) { // 跳过当前目录(.)和上级目录(..) if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } // 拼接完整路径 char full_path[1024]; 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)) { printf("Directory: %s\n", full_path); // 递归遍历子目录 list_directory_contents(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; } list_directory_contents(argv[1]); return 0; } 

这个程序接受一个目录路径作为参数,并使用 readdir 函数遍历该目录及其所有子目录。对于每个文件和目录,它会打印出其完整路径。如果遇到子目录,程序会递归地遍历它。

0