利用 readdir 函数能够逐一访问目录并生成文件列表。下面是一个基于 C 语言实现的例子,展示如何借助 readdir 函数来读取指定目录内的所有文件与子目录,并将其保存到一个列表中:
#include#include #include #include 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; }
dir 函数开启当前目录(".")。借助这种方法,你就能用 readdir 函数构建出一个包含目录内所有文件及子目录的列表。