温馨提示×

linux readdir怎样获取权限

小樊
50
2026-10-05 14:44:17
栏目: 智能运维

在 Linux 下使用 readdir() 读取目录时,它本身只能拿到文件名和 inode 信息,不能直接拿到文件权限。要获取权限,需要配合 stat() / lstat() 使用。

下面按常见方式说明。


一、readdir 能拿到什么

#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、大小等


二、获取权限的标准做法(stat)

示例:遍历目录并打印权限

#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) // 目录

四、readdir + d_type 的“半获取”(不推荐用于权限)

d_type 只能判断类型,不能判断权限:

if (entry->d_type == DT_REG) // 普通文件

⚠️ 某些文件系统(如部分 NFS)d_type 可能是 DT_UNKNOWN


五、不想多次 stat?用 scandir / getdents(进阶)

  • scandir():方便但仍是 readdir + stat
  • getdents64():底层,但仍不含权限
  • 没有“一次系统调用拿到权限”的目录遍历方式

六、总结

需求 方法
读目录 opendir + readdir
获取权限 stat() / lstat()
符号链接本身权限 lstat()
仅类型 d_type

如果你愿意,我可以给你:

  • ✅ 完整可编译示例
  • ✅ 类似 ls -l 的权限字符串输出
  • ✅ C++ / Python 版本

直接说你用的语言即可。

0 踩