直接上代码:
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
//计算某目录所占空间大小(包含本身的4096Byte)
long long int GetDirectorySize(char *dir)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
long long int totalSize=0;
if ((dp = opendir(dir)) == NULL)
{
fprintf(stderr, "Cannot open dir: %s\n", dir);
return -1; //可能是个文件,或者目录不存在
}
//先加上自身目录的大小
lstat(dir, &statbuf);
totalSize+=statbuf.st_size;
while ((entry = readdir(dp)) != NULL)
{
char subdir[256];
sprintf(subdir, "%s/%s", dir, entry->d_name);
lstat(subdir, &statbuf);
if (S_ISDIR(statbuf.st_mode))
{
if (strcmp(".", entry->d_name) == 0 ||
strcmp("..", entry->d_name) == 0)
{
continue;
}
long long int subDirSize = GetDirectorySize(subdir);
totalSize+=subDirSize;
}
else
{
totalSize+=statbuf.st_size;
}
}
closedir(dp);
return totalSize;
}
int main(int argc, char* argv[])
{
char* dir = argv[1];
long long int totalSize = GetDirectorySize(dir);
printf("totalSize: %lld\n", totalSize);
return 0;
}