
利用 readdir 函数能够逐一访问目录并生成文件列表。下面是一个基于 C 语言实现的例子,展示如何借助 readdir 函数来读取指定目录内的所有文件与子目录,并将其保存到一个列表中:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main() {
DIR *directory;
struct dirent *file_entry;
char full_path[1024];
// 初始化并打开目标目录
directory = opendir(".");
if (directory == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
// 循环处理目录里的每一项
while ((file_entry = readdir(directory)) != NULL) {
// 排除掉当前目录和上一级目录的特殊条目
if (strcmp(file_entry->d_name, ".") == 0 || strcmp(file_entry->d_name, "..") == 0) {
continue;
}
// 拼接成完整的路径
snprintf(full_path, sizeof(full_path), "./%s", file_entry->d_name);
// 输出文件或子目录的名字
printf("%s\n", full_path);
}
// 关闭已打开的目录
closedir(directory);
return EXIT_SUCCESS;
}借助这种方法,你就能用 readdir 函数构建出一个包含目录内所有文件及子目录的列表。
以上就是如何用readdir创建文件列表的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号