在Linux中,readdir
函数用于读取目录中的条目。要获取文件类型,您可以使用stat
函数来获取文件的详细信息,然后检查文件类型。
以下是一个简单的示例,展示了如何使用readdir
和stat
函数来获取目录中的文件类型:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
dir = opendir("."); // 打开当前目录
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录(".")和上级目录("..")
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 获取文件的详细信息
if (stat(entry->d_name, &file_stat) == -1) {
perror("stat");
continue;
}
// 检查文件类型
switch (file_stat.st_mode & S_IFMT) {
case S_IFREG:
printf("%s: 普通文件\n", entry->d_name);
break;
case S_IFDIR:
printf("%s: 目录\n", entry->d_name);
break;
case S_IFCHR:
printf("%s: 字符设备\n", entry->d_name);
break;
case S_IFBLK:
printf("%s: 块设备\n", entry->d_name);
break;
case S_IFIFO:
printf("%s: 管道\n", entry->d_name);
break;
case S_IFSOCK:
printf("%s: 套接字\n", entry->d_name);
break;
default:
printf("%s: 未知类型\n", entry->d_name);
break;
}
}
closedir(dir);
return 0;
}
这个示例程序首先打开当前目录,然后使用readdir
函数读取目录中的每个条目。对于每个条目,它使用stat
函数获取文件的详细信息,然后检查st_mode
字段以确定文件类型。最后,它输出每个文件的类型。