
本文介绍如何利用 copendir 函数和 readdir 函数递归遍历目录结构。 以下代码示例展示了这一过程:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <limits.h> // Include for PATH_MAX
void traverseDirectory(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; // Skip "." and ".." entries
}
char fullPath[PATH_MAX];
snprintf(fullPath, PATH_MAX, "%s/%s", path, entry->d_name);
struct stat statbuf;
if (stat(fullPath, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
printf("Directory: %s\n", fullPath);
traverseDirectory(fullPath); // Recursive call for subdirectories
} else {
printf("File: %s\n", fullPath);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
traverseDirectory(argv[1]);
return EXIT_SUCCESS;
}代码功能说明:
opendir(path) 函数打开指定的目录。readdir(dir) 函数逐个读取目录中的文件和子目录信息。snprintf 函数构建每个文件或子目录的完整路径。stat(fullPath, &statbuf) 获取文件状态信息,用于判断是文件还是目录。statbuf 指示是目录 (S_ISDIR),则递归调用 traverseDirectory 函数处理子目录。closedir(dir) 关闭打开的目录流,释放资源。使用方法:
.c 文件 (例如 listdir.c)。gcc -o listdir listdir.c
./listdir /path/to/your/directory
此程序将打印出指定目录及其所有子目录中所有文件和子目录的完整路径。 请确保您具有访问指定目录的权限。 添加了 limits.h 头文件和 PATH_MAX 常量,以确保路径长度的正确处理,避免缓冲区溢出。
以上就是copendir如何遍历目录结构的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号