centos

CentOS readdir如何获取文件属性信息

小樊
43
2025-06-20 13:30:17
栏目: 智能运维

在 CentOS 系统中,你可以使用 readdir 函数来读取目录中的文件,并结合其他函数来获取文件的属性信息。readdir 函数本身只返回目录中的文件名,要获取文件的详细属性信息,你需要使用 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");
        exit(EXIT_FAILURE);
    }

    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("Last modified: %s", ctime(&file_stat.st_mtime));
    }

    closedir(dir);
    return 0;
}

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

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

gcc -o file_attributes file_attributes.c

然后运行生成的可执行文件:

./file_attributes

这将显示当前目录中所有文件的属性信息。

0
看了该问题的人还看了