温馨提示×

如何用readdir获取文件属性

小樊
45
2025-09-17 14:38:58
栏目: 编程语言

在C语言中,使用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;

    // 打开目录
    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 path[1024];
        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);
        printf("Last modified: %s", ctime(&file_stat.st_mtime));
    }

    // 关闭目录
    closedir(dir);

    return EXIT_SUCCESS;
}

这个示例程序首先打开当前目录(.),然后使用readdir读取目录中的每个条目。对于每个条目,它跳过当前目录和上级目录,然后构建文件的完整路径。接下来,它使用stat函数获取文件的属性,并输出文件名、大小、权限和最后修改时间。

注意:在实际应用中,你可能需要根据实际需求对代码进行调整。例如,你可能需要处理符号链接、错误处理等。

0