
利用 readdir 实现递归式目录浏览通常包含如下几个阶段:
以下为一段采用 C 语言编写的递归目录浏览示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
// 函数声明
void recursive_readdir(const char *path);
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "用法: %s \n", argv[0]);
return EXIT_FAILURE;
}
const char *start_path = argv[1];
recursive_readdir(start_path);
return EXIT_SUCCESS;
}
void recursive_readdir(const char *path) {
DIR *dir = opendir(path);
if (dir == NULL) {
perror("无法打开目录");
return;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录和父目录
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
// 构造完整路径
size_t len = strlen(path) + strlen(entry->d_name) + 2; // +1 for '/' and +1 for '\0'
char full_path[len];
snprintf(full_path, len, "%s/%s", path, entry->d_name);
struct stat st;
if (stat(full_path, &st) == -1) {
perror("无法获取文件状态");
continue;
}
if (S_ISDIR(st.st_mode)) {
// 如果是目录,递归浏览
printf("目录: %s\n", full_path);
recursive_readdir(full_path);
} else {
// 如果是文件,进行处理(这里以打印文件名为例)
printf("文件: %s\n", full_path);
}
}
closedir(dir);
}主函数 (main):
递归浏览函数 (recursive_readdir):
将上述代码保存为 recursive_readdir.c,随后使用以下命令进行编译与运行:
<code>gcc -o recursive_readdir recursive_readdir.c ./recursive_readdir /path/to/directory</code>
将 /path/to/directory 替换为目标目录的实际路径。
通过上述方式,你能借助 readdir 实现递归目录浏览,适用于多种需在程序中处理文件系统的场景。
以上就是如何用readdir实现递归目录遍历的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号