阅读量:2
在Linux中,readdir函数用于读取目录中的条目。默认情况下,readdir会返回目录中的所有文件和子目录,不论它们的类型。如果你想要对不同类型的文件执行不同的操作,你需要在读取到每个条目后,使用其他函数来检查它的类型。
以下是一个简单的示例,展示了如何使用readdir以及stat函数来区分目录中的文件类型:
#include
#include
#include
#include
#include
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
if (argc != 2) {
fprintf(stderr, "Usage: %s \n" , argv[0]);
return EXIT_FAILURE;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
// 构建文件的完整路径
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
// 获取文件的stat信息
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 检查文件类型
if (S_ISREG(file_stat.st_mode)) {
printf("Regular file: %s\n", entry->d_name);
} else if (S_ISDIR(file_stat.st_mode)) {
printf("Directory: %s\n", entry->d_name);
} else if (S_ISCHR(file_stat.st_mode)) {
printf("Character device: %s\n", entry->d_name);
} else if (S_ISBLK(file_stat.st_mode)) {
printf("Block device: %s\n", entry->d_name);
} else if (S_ISFIFO(file_stat.st_mode)) {
printf("FIFO (named pipe): %s\n", entry->d_name);
} else if (S_ISSOCK(file_stat.st_mode)) {
printf("Socket: %s\n", entry->d_name);
} else {
printf("Other type: %s\n", entry->d_name);
}
}
closedir(dir);
return EXIT_SUCCESS;
}
这个程序接受一个目录路径作为命令行参数,然后使用opendir打开该目录,使用readdir读取目录中的每个条目。对于每个条目,它使用stat函数获取文件的详细信息,并根据st_mode字段检查文件类型。
注意,这个程序只是一个简单的示例,实际使用时可能需要处理更多的错误情况和边缘情况。
以上就是关于“Linux readdir如何支持多种文件类型”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm