在Linux中,readdir函数用于读取目录中的文件和子目录。要实现目录筛选,你可以结合opendir、readdir和closedir函数,并使用dirent.h头文件中定义的结构体和常量。以下是一个简单的示例,展示了如何使用这些函数来筛选特定类型的文件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
char path[1024];
if (argc != 2) {
printf("Usage: %s <directory>\n", argv[0]);
return 1;
}
// 打开目录
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
// 遍历目录中的文件和子目录
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录(.)和上级目录(..)
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 拼接文件或目录的完整路径
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
// 获取文件或目录的状态信息
if (stat(path, &file_stat) == -1) {
perror("stat");
closedir(dir);
return 1;
}
// 根据需要筛选文件类型,例如只显示普通文件
if (S_ISREG(file_stat.st_mode)) {
printf("%s\n", path);
}
}
// 关闭目录
closedir(dir);
return 0;
}
这个示例程序接受一个命令行参数,表示要筛选的目录。它会遍历该目录中的所有文件和子目录,并使用stat函数获取每个条目的状态信息。然后,它检查文件类型(通过S_ISREG宏),并仅打印普通文件的路径。
你可以根据需要修改筛选条件,例如使用S_ISDIR宏来筛选目录,或者使用其他文件属性和函数来实现更复杂的筛选逻辑。