在linux中,readdir函数被广泛用于读取目录中的文件和子目录。本文将通过一个简单的示例,展示如何使用readdir函数来读取目录并判断文件类型。
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <limits.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
if (argc != 2) {
printf("使用方法: %s <目录>\n", argv[0]);
return 1;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("无法打开目录");
return 1;
}
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("获取文件信息失败");
continue;
}
// 判断文件类型
if (S_ISREG(file_stat.st_mode)) {
printf("%s 是一个普通文件\n", entry->d_name);
} else if (S_ISDIR(file_stat.st_mode)) {
printf("%s 是一个目录\n", entry->d_name);
} else if (S_ISCHR(file_stat.st_mode)) {
printf("%s 是一个字符设备\n", entry->d_name);
} else if (S_ISBLK(file_stat.st_mode)) {
printf("%s 是一个块设备\n", entry->d_name);
} else if (S_ISFIFO(file_stat.st_mode)) {
printf("%s 是一个FIFO(命名管道)\n", entry->d_name);
} else if (S_ISSOCK(file_stat.st_mode)) {
printf("%s 是一个套接字\n", entry->d_name);
} else {
printf("%s 是一个未知类型的文件\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
上述程序接收一个目录作为命令行参数,并使用readdir函数读取该目录中的每个条目。对于每个条目,我们利用stat函数获取文件的stat信息,并根据st_mode字段来判断文件类型。这样,我们就能轻松地识别出目录中的各种文件类型,如普通文件、目录、字符设备、块设备、命名管道和套接字等。
魔众SCRM私域运营平台是一个在线CRM管理平台,支持多企业多租户模式,具有高扩展性,支持一站式私域流量运营平台。魔众SCRM私域运营平台,一站式私域流量运营平台。2023年10月02日魔众SCRM私域运营系统发布v5.8.0版本,增加了以下30个特性:·[新功能] 移动端增加c-rich-html组件,支持多端富文本兼容显示·[新功能] MS.Util.browser 浏览器判断工具类·[新功能
0
以上就是Linux readdir文件类型判断的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号