在 Linux 下使用 readdir() 读取目录时,它本身只能拿到文件名和 inode 信息,不能直接拿到文件权限。要获取权限,需要配合 stat() / lstat() 使用。
下面按常见方式说明。
#include <dirent.h>
struct dirent {
ino_t d_ino;
off_t d_off;
unsigned short d_rendtl;
unsigned char d_type; // 文件类型(DT_REG / DT_DIR 等)
char d_name[]; // 文件名
};
✅ 有:文件名、类型
❌ 没有:权限(mode)、uid、gid、大小等
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
const char *path = argv[1];
DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
char full[1024];
snprintf(full, sizeof(full), "%s/%s", path, entry->d_name);
struct stat st;
if (stat(full, &st) == -1) {
perror("stat");
continue;
}
// 权限在 st_mode 中
printf("%s mode: %o\n", entry->d_name, st.st_mode & 0777);
}
closedir(dir);
return 0;
}
权限在 struct stat 的 st_mode 中:
st.st_mode & S_IRWXU // 用户权限
st.st_mode & S_IRWXG // 组权限
st.st_mode & S_IRWXO // 其他权限
或使用宏:
S_ISREG(st.st_mode) // 普通文件
S_ISDIR(st.st_mode) // 目录
d_type 只能判断类型,不能判断权限:
if (entry->d_type == DT_REG) // 普通文件
⚠️ 某些文件系统(如部分 NFS)d_type 可能是 DT_UNKNOWN
scandir():方便但仍是 readdir + statgetdents64():底层,但仍不含权限| 需求 | 方法 |
|---|---|
| 读目录 | opendir + readdir |
| 获取权限 | stat() / lstat() |
| 符号链接本身权限 | lstat() |
| 仅类型 | d_type |
如果你愿意,我可以给你:
ls -l 的权限字符串输出直接说你用的语言即可。