在Linux中,你可以使用readdir
函数来读取目录中的文件。如果你想要过滤特定类型的文件,可以在遍历目录时检查每个文件的扩展名。以下是一个简单的示例,展示了如何使用C语言和dirent.h
库来实现这个功能:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir("."); // 打开当前目录
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
// 检查文件扩展名,例如只显示.txt文件
if (strstr(entry->d_name, ".txt") != NULL) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
在这个示例中,我们使用opendir
函数打开当前目录,然后使用readdir
函数逐个读取目录中的文件。对于每个文件,我们使用strstr
函数检查文件名是否包含.txt
字符串。如果包含,我们就打印出文件名。
你可以根据需要修改这个示例,以便过滤其他类型的文件。只需将.txt
替换为你想要过滤的文件扩展名即可。