计算一个目录文件下的文件大小
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int get_dir_size( const char * pathname)
{
int size = 0;
DIR *dir = opendir(pathname);
if(dir == NULL)
{
perror("opendir error\n");
return -1;
}
struct dirent *dirp = NULL ;
while( dirp = readdir(dir) )
{
if( ( strcmp(dirp->d_name,".")==0 ) || ( strcmp(dirp->d_name,"..")==0 ) )
{
continue;
}
char filename[512];
sprintf(filename ,"%s/%s",pathname,dirp->d_name);
struct stat st;
int ret = 0;
ret =lstat(filename,&st);
if(ret == -1)
{
perror("lstat error\n");
return -2;
}
if(S_ISREG(st.st_mode))
{
size += st.st_size;
}
else if(S_ISDIR(st.st_mode))
{
int s = get_dir_size(filename);
size += ((s==-1)? 0:s);
}
}
closedir(dir);
return size;
}
int main(int argc ,char *argv[])
{
printf("size = %d\n" ,get_dir_size(argv[1]));
}