
readdir 是一个用于读取目录内容的函数,通常与 opendir、closedir 和其他文件操作函数一起使用。下面是一个简单的示例,展示了如何通过这些函数遍历指定目录及其子目录中的所有文件和文件夹:
<code>#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.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[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
// 获取文件或目录的信息
if (stat(full_path, &path_stat) == -1) {
perror("stat");
continue;
}
// 输出路径名称
printf("%s\n", full_path);
// 如果是目录类型,则递归调用
if (S_ISDIR(path_stat.st_mode)) {
list_directory_contents(full_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;
}
</string.h></sys/stat.h></dirent.h></stdlib.h></stdio.h></code>该程序接收一个目录路径作为输入参数,并通过 opendir 打开目标目录。随后利用 readdir 函数逐项读取目录内容。在处理每个条目时,通过 stat 函数获取具体信息并输出其完整路径。若识别出子目录,则会触发递归操作继续深入遍历。
注意:此代码未涉及符号链接或其他特殊文件类型的处理。实际开发中可根据需要增加相应的判断逻辑。
以上就是readdir如何与其他文件操作函数配合使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号