linux

readdir如何获取文件所有者

小樊
43
2025-07-28 15:17:31
栏目: 编程语言

在Linux系统中,readdir函数用于读取目录中的条目。但是,readdir本身并不直接提供文件所有者的信息。要获取文件所有者,你需要结合其他函数和系统调用。以下是一个使用readdirstat函数获取文件所有者的示例:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <pwd.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 1;
    }

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

    while ((entry = readdir(dir)) != NULL) {
        // 跳过当前目录和上级目录
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 构建文件的完整路径
        char file_path[PATH_MAX];
        snprintf(file_path, sizeof(file_path), "%s/%s", argv[1], entry->d_name);

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

        // 获取文件所有者
        struct passwd *owner = getpwuid(file_stat.st_uid);
        if (owner == NULL) {
            perror("getpwuid");
            continue;
        }

        printf("File: %s\nOwner: %s\n", entry->d_name, owner->pw_name);
    }

    closedir(dir);
    return 0;
}

这个程序首先打开一个目录,然后使用readdir读取目录中的每个条目。对于每个条目,它使用stat函数获取文件的元数据,然后使用getpwuid函数根据文件的UID查找文件所有者的用户名。最后,它输出文件名和文件所有者。

要编译这个程序,请使用以下命令:

gcc -o get_file_owner get_file_owner.c

然后运行程序,传入一个目录作为参数:

./get_file_owner /path/to/directory

这将输出目录中每个文件的所有者。

0
看了该问题的人还看了