在Linux中,readdir
函数用于读取目录中的条目。要实现递归遍历目录,你需要结合opendir
、readdir
和closedir
函数,并对每个子目录调用递归函数。以下是一个简单的C语言示例,展示了如何使用这些函数递归遍历目录:
#include#include #include #include #include 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 \n", argv[0]); return EXIT_FAILURE; } list_directory_contents(argv[1]); return EXIT_SUCCESS; }
这个程序接受一个命令行参数,即要遍历的目录路径。它会打开目录,读取其中的每个条目,并检查它们是文件还是目录。如果是目录,它会递归地调用list_directory_contents
函数;如果是文件,它会打印文件的完整路径。
要编译这个程序,你可以使用gcc
:
gcc -o listdir listdir.c
然后运行它,传入你想要遍历的目录路径:
./listdir /path/to/directory
请注意,这个程序没有处理符号链接,如果目录中包含指向其他目录的符号链接,它可能会导致无限递归。此外,错误处理也比较简单,实际使用中可能需要更详细的错误检查和处理。