Linux 获取当前文件夹下大小最大的前 n 个文件

du -s * | sort -nr | head -n 10         # 获取大小最大的10个文件

du -s * | sort -nr | tail -n 10         # 获取大小最小的10个文件

 

你可以使用递归的方式遍历 `/tmp` 目录及其子目录下的所有文件文件夹,并使用 `stat` 系统调用获取文件大小,最终统计出每个文件夹大小和每个文件大小,再找出占内存最大文件夹文件。 以下是一个示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <sys/stat.h> #include <string.h> // 定义一个结构体用于存储文件夹大小和路径 struct FolderSize { long long size; char path[1024]; }; // 递归遍历目录 void traverse_dir(const char *dir_path, long long *total_size, struct FolderSize *max_folder) { DIR *dir = opendir(dir_path); if (dir == NULL) { perror("opendir"); return; } struct dirent *entry; struct stat st; long long folder_size = 0; while ((entry = readdir(dir)) != NULL) { // 构造文件路径 char path[1024]; snprintf(path, sizeof(path), "%s/%s", dir_path, entry->d_name); if (stat(path, &st) == -1) { perror("stat"); continue; } if (S_ISDIR(st.st_mode)) { // 如果是目录,则递归遍历 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } traverse_dir(path, &folder_size, max_folder); } else if (S_ISREG(st.st_mode)) { // 如果是普通文件,则累加文件大小 folder_size += st.st_size; *total_size += st.st_size; // 如果文件大小当前最大文件夹还大,则更新最大文件夹信息 if (folder_size > max_folder->size) { max_folder->size = folder_size; strncpy(max_folder->path, dir_path, sizeof(max_folder->path)); } } } closedir(dir); printf("Folder %s size: %lld bytes\n", dir_path, folder_size); } int main() { long long total_size = 0; struct FolderSize max_folder = {0, ""}; traverse_dir("/tmp", &total_size, &max_folder); printf("Total size of /tmp and its subdirectories: %lld bytes\n", total_size); printf("Largest folder: %s (%lld bytes)\n", max_folder.path, max_folder.size); return 0; } ``` 注意,在程序中使用了 `strncpy` 函数来复制文件夹路径,以防止路径溢出问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘广宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值