在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