问题引入:
假设定义一个目录的大小为,该目录下面以及其所有子目录,所有的普通文件的大小之和,请写一个函数求一个目录的大小。
(Linux系统注意:过滤掉 . 和 . . 这两个隐藏文件夹)
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
int get_dir_size(char *path)// /home/gec
{
int size = 0;
//打开目录
DIR*dir = opendir(path);
if(dir == NULL)
{
perror("opendir error:");
return -1;
}
//不断的读取目录,获取目录项
struct dirent*dirent;
while(dirent = readdir(dir))
{
//过滤到 . 和 ..
if(strcmp(dirent->d_name,".") == 0 || strcmp(dirent->d_name,"..") == 0)
{
continue;
}
//获取文件的完整路径
char pathname[512] = {0};
sprintf(pathname,"%s/%s",path,dirent->d_name);
struct stat st;
stat(pathname,&st);
//普通文件
if(dirent->d_type == DT_REG)
{
size += st.st_size;
}
//目录文件
else if(dirent->d_type == DT_DIR)
{
size += get_dir_size(pathname);
}
}
//关闭目录
closedir(dir);
return size;
}
//主函数
int main(int argc,char**argv)
{
int s = get_dir_size(argv[1]);
printf("大小之和为:s = %d\n",s);
}