一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Linux readdir怎样实现过滤功能

时间:2026-07-25 18:15:54 编辑:袖梨 来源:一聚教程网

在Linux中,readdir函数用于读取目录中的文件和子目录。要实现过滤功能,您可以在调用readdir之后对返回的dirent结构体进行检查,根据需要决定是否处理某个文件或子目录。

Linux readdir如何实现过滤功能

以下是一个简单的示例,展示了如何使用readdirdirent.h库实现过滤功能:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <dirent.h>#include <sys/types.h>#include <sys/stat.h>int main(int argc, char *argv[]) {DIR *dir;struct dirent *entry;char path[1024];if (argc != 2) {fprintf(stderr, "Usage: %s <directory>n", argv[0]);return EXIT_FAILURE;}// 打开目录dir = opendir(argv[1]);if (!dir) {perror("opendir");return EXIT_FAILURE;}// 遍历目录中的文件和子目录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);// 获取文件信息struct stat file_stat;if (stat(path, &file_stat) == -1) {perror("stat");continue;}// 检查文件类型和名称,根据需要进行过滤if (S_ISREG(file_stat.st_mode) && strstr(entry->d_name, "txt")) {printf("Regular file with 'txt' extension: %sn", entry->d_name);} else if (S_ISDIR(file_stat.st_mode)) {printf("Directory: %sn", entry->d_name);}}// 关闭目录closedir(dir);return EXIT_SUCCESS;}

在这个示例中,我们遍历指定目录中的所有文件和子目录,并检查它们的类型和名称。如果文件是常规文件并且名称包含"txt",则打印出来。如果是一个目录,则打印目录名。您可以根据需要修改过滤条件。

编译并运行这个程序,传入一个目录作为参数,它将输出符合条件的文件和子目录。

热门栏目