linux

readdir如何获取文件属性

小樊
33
2025-03-25 11:46:17
栏目: 编程语言
开发者专用服务器限时活动,0元免费领! 查看>>

readdir 函数本身并不直接提供文件属性信息,它主要用于读取目录中的条目。但是,你可以结合其他函数来获取文件的属性。在C语言中,你可以使用 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;

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

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

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

        // 获取文件属性
        if (stat(file_path, &file_stat) == 0) {
            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));
        } else {
            perror("stat");
        }
    }

    // 关闭目录
    closedir(dir);

    return EXIT_SUCCESS;
}

这个示例程序首先打开当前目录(.),然后使用 readdir 函数读取目录中的每个条目。对于每个条目,我们使用 snprintf 函数构建文件的完整路径,然后使用 stat 函数获取文件的属性。最后,我们打印文件名、大小和最后修改时间。

请注意,这个示例仅适用于类Unix系统(如Linux和macOS)。在Windows上,你需要使用不同的函数(如 FindFirstFileFindNextFile)来读取目录中的条目,并使用 GetFileAttributesEx 函数获取文件属性。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:linux readdir怎样获取文件属性

0
看了该问题的人还看了