答主之前文章有介绍文件IO内容,下边题目就是对之前内容的具体应用。
问题:假设一个目录的大小为这个目录下所有普通文件的大小
写一个函数用来求一个目录的大小 (子目录下的也要)
思路:
//打开目录
//不断的获取目录项
while()
{
//进行具体操作
//判断文件类型
if()//普通文件
{
//求大小
}
else if()//目录文件
{
//把子目录的大小获取
}
}
//关闭目录
代码实现:
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
/*
get_dir_size:获取目录的大小
@pathname :要获取的目录的路径名
返回值:
成功返回目录大小
失败返回-1
*/
int get_dir_size(const char*pathname)
{
int size = 0;
//打开目录
DIR* dir = opendir(pathname);
if(dir == NULL)
{
perror("open opendir error:");
return -1;
}
//不断的获取目录项
struct dirent *d = NULL;
while(d = readdir(dir))
{
//进行具体操作
//进行路径名的拼接
char dir_pathname[512] = {0};
sprintf(dir_pathname,"%s/%s",pathname,d->d_name);
//判断文件类型
if(d->d_type == DT_REG)//普通文件
{
//求大小
struct stat st;
stat(dir_pathname,&st);
size += st.st_size;
}
else if(d->d_type == DT_DIR)//目录文件
{
//把 . 和.. 过滤
if(strcmp(d->d_name,".") == 0 || strcmp(d->d_name,"..") == 0)
{
continue;
}
//把子目录的大小获取
size += get_dir_size(dir_pathname);
}
}
//关闭目录
closedir(dir);
return size;
}
int main(int argc,char**argv)
{
int s = get_dir_size(argv[1]);
printf("s = %d\n",s);
}