linux

Linux copendir如何获取目录下文件的大小

小樊
41
2025-06-18 00:45:08
栏目: 智能运维

在 Linux 中,copendir() 函数用于打开一个目录流,以便你可以使用 readdir() 函数读取目录中的条目。要获取目录下文件的大小,你需要结合使用这些函数以及其他一些系统调用,如 stat()

下面是一个简单的示例,展示了如何使用 copendir()readdir()stat() 来获取目录下每个文件的大小:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>

int main(int argc, char *argv[]) {
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;
    char path[PATH_MAX];

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>
", argv[0]);
        return EXIT_FAILURE;
    }

    dir = opendir(argv[1]);
    if (dir == NULL) {
        perror("opendir");
        return EXIT_FAILURE;
    }

    while ((entry = readdir(dir)) != NULL) {
        // Skip current and parent directory entries
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // Construct the full path to the file
        snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);

        // Get file status
        if (stat(path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        // Check if it's a regular file and print its size
        if (S_ISREG(file_stat.st_mode)) {
            printf("%s: %ld bytes
", entry->d_name, file_stat.st_size);
        }
    }

    closedir(dir);
    return EXIT_SUCCESS;
}

说明:

  1. 打开目录:使用 opendir() 打开一个目录流。
  2. 读取目录条目:使用 readdir() 函数读取目录中的每个条目。
  3. 构建文件路径:使用 snprintf() 构建文件的完整路径。
  4. 获取文件状态:使用 stat() 函数获取文件的状态信息,包括大小。
  5. 检查文件类型:使用 S_ISREG() 宏检查条目是否为常规文件。
  6. 打印文件大小:如果是常规文件,则打印其大小。

编译并运行这个程序时,传入一个目录路径作为参数,它将输出该目录下所有常规文件的大小。

0
看了该问题的人还看了