C语言求一个目录的大小

答主之前文章有介绍文件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);
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值