在 Linux 中,opendir
函数用于打开一个目录流,但本身并不提供递归遍历功能。要实现递归目录遍历,通常需要结合其他函数如 readdir
、closedir
以及 stat
来检查每个条目是否为目录,并在是目录时递归调用遍历函数。
下面是一个使用 C 语言实现的递归目录遍历示例:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
// 递归遍历目录的函数
void recursive_directory_traversal(const char *path) {
DIR *dir = opendir(path);
if (dir == NULL) {
// 如果无法打开目录,输出错误信息并返回
perror("opendir");
return;
}
struct dirent *entry;
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);
struct stat path_stat;
if (stat(full_path, &path_stat) == -1) {
// 如果无法获取文件状态,输出错误信息并继续
perror("stat");
continue;
}
if (S_ISDIR(path_stat.st_mode)) {
// 如果是目录,递归调用
printf("进入目录: %s\n", full_path);
recursive_directory_traversal(full_path);
} else {
// 如果是文件,打印文件名
printf("文件: %s\n", full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "用法: %s <目录路径>\n", argv[0]);
return EXIT_FAILURE;
}
const char *start_path = argv[1];
printf("开始遍历目录: %s\n", start_path);
recursive_directory_traversal(start_path);
printf("遍历完成。\n");
return EXIT_SUCCESS;
}
包含必要的头文件:
stdio.h
、stdlib.h
:用于标准输入输出和通用工具函数。dirent.h
:用于目录操作。sys/stat.h
和 string.h
:用于文件状态检查和字符串操作。errno.h
:用于错误处理。recursive_directory_traversal
函数:
opendir
打开目录流。readdir
读取目录中的每个条目。.
和 ..
这两个特殊条目。stat
获取每个条目的文件状态。closedir
关闭目录流。main
函数:
recursive_directory_traversal
开始遍历指定的起始目录。将上述代码保存为 recursive_traverse.c
,然后使用以下命令编译:
gcc -o recursive_traverse recursive_traverse.c
运行程序并指定要遍历的目录,例如:
./recursive_traverse /path/to/directory
S_ISLNK
标志来避免这种情况。perror
输出错误信息。根据实际需求,可能需要更复杂的错误处理机制。你可以根据需要对代码进行扩展,例如:
stat
获取更多文件信息,如大小、修改时间等。希望这个示例能帮助你在 Linux 中实现递归目录遍历。如果有进一步的问题,欢迎继续提问!