在Debian中,使用readdir
函数获取文件组的方法如下:
sudo apt-get update
sudo apt-get install build-essential
readdir_example.c
,并添加以下代码:#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <pwd.h>
#include <grp.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) { // 只处理普通文件
struct stat file_stat;
if (stat(argv[1] "/" entry->d_name, &file_stat) == -1) {
perror("stat");
continue;
}
gid_t file_gid = file_stat.st_gid;
struct group *group_info = getgrgid(file_gid);
if (group_info != NULL) {
printf("%s: %s\n", entry->d_name, group_info->gr_name);
} else {
printf("%s: Unknown group\n", entry->d_name);
}
}
}
closedir(dir);
return 0;
}
这段代码会遍历指定目录中的所有文件,并使用readdir
函数读取每个文件名。然后,它使用stat
函数获取文件的元数据,包括文件组ID(GID)。最后,它使用getgrgid
函数根据GID查找文件所属的组名,并将其打印出来。
gcc
编译源文件:gcc readdir_example.c -o readdir_example
./readdir_example /path/to/directory
这将输出指定目录中所有文件的名称及其所属的组名。