温馨提示×

Ubuntu readdir 如何获取文件大小

小樊
50
2025-09-20 14:23:15
栏目: 智能运维

在 Ubuntu 中,你可以使用 C 语言的 dirent.h 库来读取目录中的文件,并使用 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;

    // 打开目录
    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[1024];
        snprintf(path, sizeof(path), "./%s", entry->d_name);

        // 获取文件状态
        if (stat(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;
}

代码说明:

  1. 打开目录:使用 opendir() 函数打开当前目录(.)。

  2. 读取目录条目:使用 readdir() 函数遍历目录中的每个文件和子目录。

  3. 跳过特殊条目:跳过 ... 这两个特殊的目录条目。

  4. 构建文件路径:使用 snprintf() 函数构建文件的完整路径。

  5. 获取文件状态:使用 stat() 函数获取文件的状态信息,包括文件大小(st_size 字段)。

  6. 输出文件信息:打印文件名和大小。

  7. 关闭目录:使用 closedir() 函数关闭目录。

编译并运行这个程序,你将看到当前目录中所有文件的名称和大小。确保你有权限访问这些文件和目录。

0