Linux目录大小统计:编写符合指定规则的C语言程序需求
C语言程序:计算目录及其子目录的总文件大小(含目录、不解析符号链接)
嘿,我来帮你搞定这个需求!下面是一个完整的C语言实现,完全符合你提到的要求——统计指定目录(包括顶层目录、所有子目录本身,以及所有文件)的总大小,而且遇到符号链接时只会统计链接文件自身的大小,不会去解引用它指向的内容。程序支持命令行传参指定目标目录,非常方便测试。
完整代码实现
#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <sys/stat.h> #include <string.h> #include <errno.h> // 递归计算目录及子目录的总大小 off_t calculate_total_size(const char *path) { DIR *dir = opendir(path); if (!dir) { fprintf(stderr, "无法打开目录 %s: %s\n", path, strerror(errno)); return 0; } struct dirent *entry; struct stat stat_buf; off_t total_size = 0; char full_path[PATH_MAX]; // 先统计当前目录本身的大小 if (lstat(path, &stat_buf) == 0) { total_size += stat_buf.st_size; } else { fprintf(stderr, "无法获取目录 %s 的信息: %s\n", path, strerror(errno)); } while ((entry = readdir(dir)) != NULL) { // 跳过当前目录和父目录,避免无限递归 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } // 拼接完整路径 snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name); // 获取文件信息,用lstat而非stat,不跟随符号链接 if (lstat(full_path, &stat_buf) == -1) { fprintf(stderr, "无法获取文件 %s 的信息: %s\n", full_path, strerror(errno)); continue; } // 如果是目录,递归处理子目录 if (S_ISDIR(stat_buf.st_mode)) { total_size += calculate_total_size(full_path); } else { // 普通文件、符号链接等,直接累加大小 total_size += stat_buf.st_size; } } closedir(dir); return total_size; } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "用法: %s <目标目录路径>\n", argv[0]); return EXIT_FAILURE; } off_t total = calculate_total_size(argv[1]); printf("目录 %s 的总大小(含所有子目录及文件): %lld 字节\n", argv[1], (long long)total); return EXIT_SUCCESS; }
关键细节说明
- 符号链接处理:使用
lstat()而非stat(),这样我们获取的是符号链接文件本身的大小,而不是它指向的文件大小,完全符合你的要求。 - 递归遍历:遇到子目录时递归调用
calculate_total_size,同时跳过.和..两个特殊目录,避免陷入无限循环。 - 错误处理:对打开目录失败、获取文件信息失败的情况都做了错误提示,确保程序不会轻易崩溃,同时能告诉你哪里出了问题。
- 测试友好:通过命令行参数指定目标目录,你可以直接运行
./dirsize /your/test/dir来测试不同目录,非常方便。
编译与运行
- 将代码保存为
dirsize.c - 使用GCC编译:
gcc -o dirsize dirsize.c - 运行程序:
./dirsize /path/to/your/directory
运行后会输出目标目录的总大小(以字节为单位),包含所有子目录、目录本身、普通文件、符号链接等所有类型文件的大小。
内容的提问来源于stack exchange,提问作者Neil Shah
相关产品推荐
相关产品推荐

