在Debian系统中,readdir
函数通常用于读取目录中的文件和子目录。如果你想要对目录内容进行筛选,可以在调用readdir
之后对返回的dirent
结构体进行检查和处理。
以下是一个简单的示例,展示了如何使用readdir
函数读取目录内容,并筛选出特定类型的文件(例如,只显示.txt
文件):
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
// 打开目录
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
// 读取目录中的每个条目
while ((entry = readdir(dir)) != NULL) {
// 检查文件扩展名是否为.txt
if (strstr(entry->d_name, ".txt") != NULL) {
printf("%s\n", entry->d_name);
}
}
// 关闭目录
closedir(dir);
return EXIT_SUCCESS;
}
在这个示例中,我们首先使用opendir
函数打开当前目录(.
)。然后,我们使用readdir
函数读取目录中的每个条目。对于每个条目,我们使用strstr
函数检查文件名是否包含.txt
字符串。如果是,我们就打印出文件名。最后,我们使用closedir
函数关闭目录。
你可以根据需要修改筛选条件,例如,如果你想要筛选出特定大小的文件,可以使用stat
函数获取文件信息,并检查文件大小。