linux

readdir如何获取文件大小信息

小樊
48
2025-08-14 12:01:35
栏目: 编程语言

readdir 函数本身并不直接提供文件大小信息,它主要用于读取目录中的条目。要获取文件大小信息,你需要结合其他函数,如 statfstat。以下是一个使用 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[PATH_MAX];
        snprintf(file_path, sizeof(file_path), "./%s", entry->d_name);

        // 获取文件状态信息
        if (stat(file_path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        // 输出文件名和大小
        printf("File: %s, Size: %ld bytes\n", entry->d_name, file_stat.st_size);
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

这个示例程序首先打开当前目录,然后使用 readdir 读取目录中的每个条目。对于每个条目,它使用 snprintf 构建文件的完整路径,然后使用 stat 获取文件的状态信息。stat 函数将文件状态信息存储在 file_stat 结构中,其中包括文件大小(st_size 字段)。最后,程序输出文件名和大小。

0
看了该问题的人还看了