linux

Linux copendir如何获取文件大小

小樊
35
2025-05-20 15:52:41
栏目: 智能运维

在 Linux 中,copendir() 函数用于打开一个目录流,以便你可以使用 readdir() 函数读取目录中的条目。要获取目录中文件的大小,你需要使用 stat() 函数。以下是一个简单的示例,展示了如何使用 copendir()stat() 获取目录中所有文件的大小:

#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;
    char path[1024];

    dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        return EXIT_FAILURE;
    }

    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_REG) { // 只处理普通文件
            snprintf(path, sizeof(path), "./%s", entry->d_name);
            if (stat(path, &file_stat) == 0) {
                printf("File: %s, Size: %ld bytes\n", entry->d_name, file_stat.st_size);
            } else {
                perror("stat");
            }
        }
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

这个示例程序首先使用 opendir() 打开当前目录(.),然后使用 readdir() 读取目录中的每个条目。对于每个普通文件(DT_REG),我们使用 snprintf() 构建文件的完整路径,并使用 stat() 获取文件的状态信息。file_stat.st_size 包含了文件的大小(以字节为单位)。最后,程序关闭目录流并退出。

请注意,这个示例程序仅适用于普通文件。如果你需要处理其他类型的文件(如符号链接、目录等),你需要根据 entry->d_type 进行相应的处理。

0
看了该问题的人还看了