温馨提示×

Linux readdir如何获取文件权限

小樊
37
2025-10-28 01:44:10
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的条目。要获取文件权限,你需要结合stat结构体和stat函数来使用。以下是一个简单的示例,展示了如何使用readdirstat获取目录中文件的权限:

#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <sys/stat.h> #include <unistd.h> int main(int argc, char *argv[]) { DIR *dir; struct dirent *entry; struct stat file_stat; if (argc != 2) { fprintf(stderr, "Usage: %s <directory>\n", argv[0]); return EXIT_FAILURE; } dir = opendir(argv[1]); if (dir == NULL) { perror("opendir"); return EXIT_FAILURE; } while ((entry = readdir(dir)) != NULL) { // 跳过当前目录(".")和上级目录("..") if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } // 构建文件的完整路径 char path[PATH_MAX]; snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name); // 获取文件的stat信息 if (stat(path, &file_stat) == -1) { perror("stat"); continue; } // 获取文件权限并打印 printf("%s: %s\n", entry->d_name, entry->d_name); printf("Permissions: "); printf((S_ISDIR(file_stat.st_mode)) ? "d" : "-"); printf((file_stat.st_mode & S_IRUSR) ? "r" : "-"); printf((file_stat.st_mode & S_IWUSR) ? "w" : "-"); printf((file_stat.st_mode & S_IXUSR) ? "x" : "-"); printf((file_stat.st_mode & S_IRGRP) ? "r" : "-"); printf((file_stat.st_mode & S_IWGRP) ? "w" : "-"); printf((file_stat.st_mode & S_IXGRP) ? "x" : "-"); printf((file_stat.st_mode & S_IROTH) ? "r" : "-"); printf((file_stat.st_mode & S_IWOTH) ? "w" : "-"); printf((file_stat.st_mode & S_IXOTH) ? "x" : "-"); printf("\n"); } closedir(dir); return EXIT_SUCCESS; } 

这个程序接受一个目录作为命令行参数,然后使用readdir函数读取目录中的条目。对于每个条目,它使用stat函数获取文件的stat结构体,然后从中提取文件权限并打印出来。

注意:这个示例程序仅适用于类Unix系统(如Linux)。在其他系统(如Windows)上,你需要使用不同的API来实现类似的功能。

0