linux

readdir如何获取文件属性信息

小樊
39
2025-04-12 11:59:56
栏目: 编程语言

readdir 函数用于读取目录中的条目,但它本身并不直接提供文件的属性信息。要获取文件的属性信息,你可以结合使用 readdir 和其他函数,如 stat。以下是一个简单的示例,展示了如何使用这两个函数来获取目录中文件的属性信息:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.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 函数读取目录中的每个条目。对于每个条目,它使用 stat 函数获取文件的属性信息,并将其打印到屏幕上。最后,它关闭目录并退出。

注意:这个示例使用了 POSIX 标准函数,因此在非 POSIX 系统(如 Windows)上可能需要使用其他函数。

0
看了该问题的人还看了