
在Linux系统下,readdir 函数被用来读取目录内的项目。假如你想对文件类型进行筛选的话,可以在调用 readdir 后检查每个项目的类型。这通常需要借助 stat 函数来获取文件的状态信息,随后依据这些信息判定文件类型。
下面是一段简化的代码片段,展示了如何在C语言中结合 readdir 和 stat 来实现文件类型筛选:
#include <stdio.h>#include <stdlib.h>#include <dirent.h>#include <sys/stat.h>#include <string.h>int main(int argc, char *argv[]) { DIR *dir; struct dirent *entry; struct stat file_stat; // 检查命令行参数是否正确 if (argc != 2) { fprintf(stderr, "Usage: %s <directory>n", argv[0]); return EXIT_FAILURE; } // 打开指定的目录 dir = opendir(argv[1]); if (dir == NULL) { perror("opendir"); return EXIT_FAILURE; } // 循环读取目录中的所有条目 while ((entry = readdir(dir)) != NULL) { // 忽略当前目录和上一级目录的特殊条目 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } // 拼接完整的文件路径 char path[PATH_MAX]; snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name); // 获取文件的状态信息 if (stat(path, &file_stat) == -1) { perror("stat"); closedir(dir); return EXIT_FAILURE; } // 根据文件类型输出相关信息 if (S_ISREG(file_stat.st_mode)) { printf("普通文件: %sn", entry->d_name); } else if (S_ISDIR(file_stat.st_mode)) { printf("目录: %sn", entry->d_name); } else if (S_ISCHR(file_stat.st_mode)) { printf("字符设备文件: %sn", entry->d_name); } else if (S_ISBLK(file_stat.st_mode)) { printf("块设备文件: %sn", entry->d_name); } else if (S_ISFIFO(file_stat.st_mode)) { printf("管道/FIFO: %sn", entry->d_name); } else if (S_ISSOCK(file_stat.st_mode)) { printf("套接字: %sn", entry->d_name); } else { printf("其他类型: %sn", entry->d_name); } } // 关闭已打开的目录 closedir(dir); return EXIT_SUCCESS;}登录后复制
文章来自互联网,不代表电脑知识网立场。发布者:,转载请注明出处:https://www.pcxun.com/n/631860.html
