root@u12d32:/opt/qy_test/size_folder# cat DIR_SIZE.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
typedef unsigned long long offf_t;
offf_t file_size(const char *filename)
{
struct stat statbuf;
if(lstat(filename, &statbuf) !=0 )
{
perror("lstat");
return -1;
}
return (statbuf.st_blocks);
}
offf_t dir_size(const char *filename)
{
DIR *dir;
struct dirent *entry;
char newfile[512];
offf_t total;
total =0;
struct stat statbuf;
if(lstat(filename, &statbuf) !=0 )
{
perror("lstat");
return -1;
}
total+=statbuf.st_blocks;
printf("%s, %d===%lld\n",__FILE__, __LINE__, total);
dir=opendir(filename);
if(!dir)
{
perror("opendir");
return -1;
}
while((entry = readdir(dir)) != NULL)
{
if(strcmp(entry->d_name,".")==0 || strcmp(entry->d_name,"..")==0) ///current dir OR parrent dir
continue;
printf("%s\n", entry->d_name);
memset(newfile,'\0',sizeof(newfile));
strcpy(newfile, filename);
strcat(newfile, "/");
strcat(newfile, entry->d_name);
printf("%s\n", newfile);
if(entry->d_type == DT_DIR)
{
total+=dir_size(newfile);
printf("%s, %d===%lld\n",__FILE__, __LINE__, total);
}
else
{
total+=file_size(newfile);
printf("%s, %d===%lld\n",__FILE__, __LINE__, total);
}
}
return total;
}
int main(int argc , char **argv)
{
offf_t sum;
if(argc < 2)
{
return -1;
}
assert(argv[1]);
sum=dir_size(argv[1]);
printf("%lu\n",(sum/2));
return 0;
}root@u12d32:/opt/qy_test/size_folder#