温馨提示×

readdir如何处理Linux文件属性

小樊
35
2025-11-23 16:12:54
栏目: 智能运维

在Linux系统中,readdir函数用于读取目录中的条目。它通常与opendirclosedir函数一起使用,以遍历目录中的所有文件和子目录。readdir函数返回一个指向dirent结构体的指针,该结构体包含有关目录条目的信息。

要处理Linux文件属性,您可以使用stat函数。stat函数接受一个文件名(或文件路径)作为参数,并返回一个stat结构体,该结构体包含了文件的详细信息,如文件类型、大小、权限等。

以下是一个简单的示例,展示了如何使用readdirstat函数遍历目录并处理文件属性:

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

int main() {
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;
    char path[1024];

    dir = opendir("."); // 打开当前目录
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

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

        // 构建文件的完整路径
        snprintf(path, sizeof(path), "./%s", entry->d_name);

        // 获取文件的属性
        if (stat(path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        // 处理文件属性
        printf("File: %s\n", entry->d_name);
        printf("Size: %ld bytes\n", file_stat.st_size);
        printf("Permissions: %o\n", file_stat.st_mode & 0777);
        printf("Last modified: %s", ctime(&file_stat.st_mtime));
    }

    closedir(dir);
    return 0;
}

这个示例程序首先打开当前目录,然后使用readdir函数遍历目录中的所有条目。对于每个条目,它构建文件的完整路径,然后使用stat函数获取文件的属性。最后,它打印出文件的大小、权限和最后修改时间等信息。

0