Linux C 计算文件夹大小数目(包括子目录、文件)
自己手工码的,并测测试可以通过。
#include
#include
#include
#include
#include
#include
/*
dirname: 要统计的文件夹路径
返回组: 计算的所有文件的数目(包括文件合目录)
*/
long get_file_count(char *dirname)
{
DIR *dir;
struct dirent *ptr;
long total_count = 0;
char path[PATH_MAX] = {0};
dir = opendir(dirname);
if(dir == NULL)
{
printf("%s: open dir: %s failed.\n", __func__,path);
exit(1);
}
while((ptr = readdir(dir)) != NULL)
{
if(strcmp(ptr->d_name,".") == 0 || strcmp(ptr->d_name,"..") == 0)
continue;
snprintf(path, (size_t)PATH_MAX, "%s/%s", dirname,ptr->d_name);
if(ptr->d_type == DT_DIR)
{
total_count ++;
//printf("%s: Entering into dir: %s.\n", __func__,path);
//printf("%s: Is dir, and count++, count: %ld\n", __func__, total_count);
total_count += get_file_count(path);
memset(path, 0, sizeof(path));
}else
{
//printf("%s: count: %ld, file: %s.\n", __func__,total_count,path);
total_count++;
}
}
closedir(dir);
//printf("%s: statistics total files count :%ld.\n", __func__,total_count);
return total_count;
}
/*
dirname: 要统计的文件夹路径
返回组: 计算的所有文件的大小
*/
long get_file_size(char *dirname) { DIR *dir; struct dirent *ptr; long total_size = 0; char path[PATH_MAX] = {0}; dir = opendir(dirname); if(dir == NULL) { printf("%s: open dir: %s failed.\n", __func__,path); exit(1); } //printf("Enetering into %s.\n", __func__); while((ptr=readdir(dir)) != NULL) { snprintf(path, (size_t)PATH_MAX, "%s/%s", dirname,ptr->d_name); struct stat buf; if(lstat(path, &buf) < 0) { printf("lstat %s error.\n", path); } if(strcmp(ptr->d_name,".") == 0) { total_size += buf.st_size; continue; } if(strcmp(ptr->d_name,"..") == 0) { continue; } //printf("buf.st_size: %ld,total_size: %ld, path: %s.\n",buf.st_size, total_size,path); if(ptr->d_type == DT_DIR) { //printf("Entering into dir: %s, total_size: %ld\n", path,total_size); total_size += get_file_size(path); //printf("Out of dir: %s, total_size: %ld\n\n", path,total_size); memset(path, 0, sizeof(path)); }else { total_size += buf.st_size; } } closedir(dir); //printf("total files size :%ld, path: %s \n", total_size,dirname); //printf("End of %s\n", __func__); return total_size; } int main(void) { long total_count = 0; long total_size = 0; total_count = get_file_count("./bin"); total_size = get_file_size("./bin"); printf("total_count:%ld, total_size:%ld\n", total_count,total_size); return 0; }