linux

copendir函数如何获取文件大小

小樊
61
2025-07-06 05:42:08
栏目: 编程语言

copendir 函数本身并不直接提供获取文件大小的功能。它的主要作用是打开一个目录流,以便你可以使用其他函数(如 readdir)来遍历目录中的条目。

要获取目录中文件的大小,你需要结合使用其他函数。以下是一个示例,展示了如何使用 opendirreaddirstat 函数来获取目录中每个文件的大小:

#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 path[PATH_MAX];
        snprintf(path, sizeof(path), "./%s", entry->d_name);

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

        // 检查是否为普通文件
        if (S_ISREG(file_stat.st_mode)) {
            printf("File: %s, Size: %ld bytes\n", entry->d_name, file_stat.st_size);
        }
    }

    // 关闭目录
    closedir(dir);

    return EXIT_SUCCESS;
}

在这个示例中,我们首先使用 opendir 打开当前目录(.)。然后,我们使用 readdir 遍历目录中的每个条目。对于每个条目,我们使用 snprintf 构建文件的完整路径,并使用 stat 获取文件的状态信息。如果文件是一个普通文件(而不是目录或其他特殊类型的文件),我们打印出文件名和大小。

请注意,这个示例仅适用于类 Unix 系统(如 Linux 和 macOS)。在 Windows 上,你需要使用不同的函数(如 _opendir、_readdir 和 _stat)。

0
看了该问题的人还看了