2021-09-23

计算一个目录文件下的文件大小

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>


/*
get_dir_size 用来获取pathname指定的目录下所有普通文件的大小
参数:
	@pathname : 要获取大小的目录的绝对路径 
返回值: 
	返回普通文件的总大小 

*/
int get_dir_size( const char * pathname) 
{
	//初始化大小为0
	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))
		{
			//如果获取子目录或子目录下的目录... 失败   
			//函数将返回-1 此时不能将-1累加到size中 
			//所以就直接设置累加0 
			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]));

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值