在Ubuntu中,你可以使用readdir函数来读取目录中的文件和子目录。但是,readdir本身并不直接提供文件大小信息。要获取文件大小,你需要结合其他函数,如stat。
以下是一个简单的示例,展示了如何在Ubuntu中使用C语言和readdir以及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 file_path[1024];
        snprintf(file_path, sizeof(file_path), "./%s", entry->d_name);
        // 获取文件状态
        if (stat(file_path, &file_stat) == -1) {
            perror("stat");
            continue;
        }
        // 输出文件名和大小
        printf("%s: %ld bytes\n", entry->d_name, file_stat.st_size);
    }
    closedir(dir);
    return EXIT_SUCCESS;
}
这个程序首先打开当前目录(.),然后使用readdir遍历目录中的每个条目。对于每个条目,它构建文件的完整路径,并使用stat函数获取文件的状态信息。stat结构体中的st_size字段包含了文件的大小(以字节为单位)。最后,程序输出每个文件的名称和大小。
要编译并运行此程序,请将其保存为get_file_size.c,然后在终端中执行以下命令:
gcc get_file_size.c -o get_file_size
./get_file_size
这将显示当前目录中所有文件的大小。