readdir 是一个用于读取目录内容的函数,通常在 C 语言中使用。要过滤特定类型的文件,你可以在遍历目录内容时检查每个文件的扩展名。以下是一个使用 readdir 过滤特定类型文件(例如,仅显示 .txt 文件)的示例:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> int main() { DIR *dir; struct dirent *entry; char path[1024]; dir = opendir("."); // 打开当前目录 if (dir == NULL) { perror("opendir"); exit(EXIT_FAILURE); } while ((entry = readdir(dir)) != NULL) { // 检查文件扩展名是否为 .txt if (strstr(entry->d_name, ".txt") != NULL) { snprintf(path, sizeof(path), "./%s", entry->d_name); printf("%s\n", path); } } closedir(dir); return 0; } 这个示例程序会打开当前目录,然后使用 readdir 遍历目录中的所有文件。对于每个文件,我们使用 strstr 函数检查文件名中是否包含 .txt 字符串。如果包含,我们就打印出文件的完整路径。
请注意,这个示例仅适用于简单的文件名过滤。如果你需要更复杂的过滤(例如,忽略大小写或支持通配符),你可能需要编写更复杂的逻辑。