linux

如何用copendir获取Linux目录的权限

小樊
50
2025-07-24 10:27:22
栏目: 智能运维

在Linux中,opendir()函数用于打开一个目录流,而不是直接获取目录的权限。但是,你可以使用opendir()结合其他函数来检查目录的权限。以下是一个使用opendir()检查目录权限的示例:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        return EXIT_FAILURE;
    }

    DIR *dir = opendir(argv[1]);
    if (dir == NULL) {
        perror("opendir");
        return EXIT_FAILURE;
    }

    struct stat dir_stat;
    if (fstat(dirfd(dir), &dir_stat) == -1) {
        perror("fstat");
        closedir(dir);
        return EXIT_FAILURE;
    }

    if (S_ISDIR(dir_stat.st_mode)) {
        printf("Directory permissions for '%s':\n", argv[1]);
        printf("Read: %s\n", (dir_stat.st_mode & S_IRUSR) ? "Yes" : "No");
        printf("Write: %s\n", (dir_stat.st_mode & S_IWUSR) ? "Yes" : "No");
        printf("Execute: %s\n", (dir_stat.st_mode & S_IXUSR) ? "Yes" : "No");

        printf("Group Read: %s\n", (dir_stat.st_mode & S_IRGRP) ? "Yes" : "No");
        printf("Group Write: %s\n", (dir_stat.st_mode & S_IWGRP) ? "Yes" : "No");
        printf("Group Execute: %s\n", (dir_stat.st_mode & S_IXGRP) ? "Yes" : "No");

        printf("Others Read: %s\n", (dir_stat.st_mode & S_IROTH) ? "Yes" : "No");
        printf("Others Write: %s\n", (dir_stat.st_mode & S_IWOTH) ? "Yes" : "No");
        printf("Others Execute: %s\n", (dir_stat.st_mode & S_IXOTH) ? "Yes" : "No");
    } else {
        fprintf(stderr, "'%s' is not a directory\n", argv[1]);
        closedir(dir);
        return EXIT_FAILURE;
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

这个程序接受一个目录作为命令行参数,然后使用opendir()打开该目录。接着,它使用fstat()函数获取目录的状态信息,并检查目录的权限。最后,它输出目录的读、写和执行权限。

要编译此程序,请将其保存为check_permissions.c,然后运行以下命令:

gcc check_permissions.c -o check_permissions

现在你可以使用这个程序来检查Linux目录的权限,例如:

./check_permissions /path/to/directory

0
看了该问题的人还看了