在Linux中,使用readdir
函数递归遍历目录需要结合opendir
、readdir
和closedir
函数。以下是一个简单的示例,展示了如何使用这些函数递归遍历目录:
#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) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
list_directory_contents(argv[1]);
return EXIT_SUCCESS;
}
这个程序接受一个命令行参数,即要遍历的目录。它首先打开目录,然后读取其中的每个条目。对于每个条目,它检查是否为目录。如果是目录,则递归调用list_directory_contents
函数;如果是文件,则输出文件名。最后,关闭目录。
编译并运行此程序,如下所示:
gcc -o list_directory_contents list_directory_contents.c
./list_directory_contents /path/to/directory
这将输出指定目录及其子目录中的所有文件和目录。