在 Ubuntu(Linux)下使用 readdir() 读取目录时,文件类型不能直接从 struct dirent 里得到完整类型,常见做法有两种:
d_type(简单、推荐优先)readdir() 返回的 struct dirent 中有一个字段:
struct dirent {
ino_t d_ino;
off_t d_off;
unsigned short d_rendtl;
unsigned char d_type; // 文件类型
char d_name[];
};
d_type 常见取值| 宏 | 含义 |
|---|---|
| DT_REG | 普通文件 |
| DT_DIR | 目录 |
| DT_LNK | 符号链接 |
| DT_CHR | 字符设备 |
| DT_BLK | 块设备 |
| DT_FIFO | 管道 |
| DT_SOCK | 套接字 |
| DT_UNKNOWN | 未知(某些文件系统不支持) |
#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s: ", entry->d_name);
switch (entry->d_type) {
case DT_REG: printf("普通文件\n"); break;
case DT_DIR: printf("目录\n"); break;
case DT_LNK: printf("符号链接\n"); break;
default: printf("其他类型\n");
}
}
closedir(dir);
return 0;
}
⚠️ 注意:
d_type 在 ext4、tmpfs 等支持DT_UNKNOWNd_type 不可用时用 stat()(最准确)如果 d_type == DT_UNKNOWN,或你需要更详细信息:
#include <sys/stat.h>
#include <unistd.h>
struct stat st;
stat(entry->d_name, &st);
if (S_ISREG(st.st_mode)) // 普通文件
if (S_ISDIR(st.st_mode)) // 目录
if (S_ISLNK(st.st_mode)) // 符号链接
S_ISREG(m)S_ISDIR(m)S_ISCHR(m)S_ISBLK(m)S_ISFIFO(m)S_ISSOCK(m)if (entry->d_type != DT_UNKNOWN) {
// 用 d_type
} else {
stat(entry->d_name, &st);
// 用 st.st_mode
}
如果你愿意,我可以给你:
你用的是 C / C++ / 脚本?