温馨提示×

CentOS readdir如何显示文件所属组

小樊
41
2025-12-21 14:51:45
栏目: 智能运维

在 CentOS 系统中,readdir 是一个用于读取目录内容的函数

以下是一个简单的示例,展示了如何使用 readdir 函数读取目录内容并显示文件所属组:

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

int main(int argc, char *argv[]) {
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;
    char group_name[256];

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

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

    while ((entry = readdir(dir)) != NULL) {
        // 获取文件的完整路径
        char file_path[1024];
        snprintf(file_path, sizeof(file_path), "%s/%s", argv[1], entry->d_name);

        // 获取文件的状态信息
        if (stat(file_path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        // 获取文件所属组
        if (getgrgid(file_stat.st_gid)->gr_name != NULL) {
            strcpy(group_name, getgrgid(file_stat.st_gid)->gr_name);
        } else {
            strcpy(group_name, "unknown");
        }

        // 输出文件名和所属组
        printf("%s: %s\n", entry->d_name, group_name);
    }

    closedir(dir);
    return 0;
}

编译并运行这个程序,传入一个目录作为参数,它将显示该目录下所有文件的名称以及它们所属的组。例如:

gcc -o list_groups list_groups.c
./list_groups /path/to/directory

这将输出类似以下内容:

file1.txt: users
file2.txt: users
file3.txt: root

0