阅读量:2
在Linux中,readdir函数用于读取目录中的条目。要区分文件类型,你可以使用stat结构体和S_ISREG、S_ISDIR等宏来检查每个条目的类型。以下是一个简单的示例,展示了如何使用readdir和stat来区分文件类型:
#include
#include
#include
#include
#include
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
if (argc != 2) {
fprintf(stderr, "Usage: %s
" , 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, &statbuf) == -1) {
perror("stat");
continue;
}
// 根据文件类型进行判断
if (S_ISREG(statbuf.st_mode)) {
printf("%s is a regular file.
", entry->d_name);
} else if (S_ISDIR(statbuf.st_mode)) {
printf("%s is a directory.
", entry->d_name);
} else if (S_ISCHR(statbuf.st_mode)) {
printf("%s is a character device.
", entry->d_name);
} else if (S_ISBLK(statbuf.st_mode)) {
printf("%s is a block device.
", entry->d_name);
} else if (S_ISFIFO(statbuf.st_mode)) {
printf("%s is a FIFO (named pipe).
", entry->d_name);
} else if (S_ISSOCK(statbuf.st_mode)) {
printf("%s is a socket.
", entry->d_name);
} else {
printf("%s is of unknown type.
", entry->d_name);
}
}
closedir(dir);
return EXIT_SUCCESS;
}
这个程序接受一个目录作为命令行参数,然后使用readdir读取目录中的每个条目。对于每个条目,它使用stat函数获取文件的状态信息,并根据st_mode字段使用宏(如S_ISREG、S_ISDIR等)来检查文件类型。然后,它打印出每个条目的类型。
以上就是关于“Linux readdir如何实现文件类型区分”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm