(linux系统)获取目录及目录下文件所占磁盘大小

运行结果

在这里插入图片描述

代码


#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <glob.h>
#include <string.h>
#define PATHSIZE 1024

static int  path_noloop(const char * path)
{
    //aa/bb/cc/..or.
    //strrchar()//在字符串中找到最右面的字符
    char *pos;
    pos= strrchr(path,'/');
    if(pos==NULL)
    {
        exit(1);
    }
    if(strcmp(pos+1,".")==0||strcmp(pos+1,"..")==0)
        return 0;
    return 1;
}
//该函数会用到递归,所以可以对变量进行优化,
//只在递归点前出现的变量可以优化到静态去。。
static int64_t mydu(const char *path)
{
    static struct stat statres;
    static char nextpath[PATHSIZE];
    glob_t globres;
    int i;
    int64_t sum;
    if(lstat(path,&statres)<0)  
    {
        perror("lstat()");
        exit(1);
    }
    //非目录文件
    if(!S_ISDIR(statres.st_mode))
    {
        return statres.st_blocks;
    }
    //目录文件/aaa/bbbb/cccc/dd
    strncpy(nextpath,path,PATHSIZE);
    strncat(nextpath,"/*",PATHSIZE);//字符串追加
    glob(nextpath,0,NULL,&globres);
    
    
    strncpy(nextpath,path,PATHSIZE);
    strncat(nextpath,"/.*",PATHSIZE);
    //追加
    glob(nextpath,GLOB_APPEND,NULL,&globres);
    
    sum=statres.st_blocks;
    for(i=0;i<globres.gl_pathc;i++)
    { 
       if(path_noloop(globres.gl_pathv[i]))
           sum+=mydu(globres.gl_pathv[i]);
    }
    globfree(&globres);
    return sum;
}


int main(int argc,char*argv[])
{
    if(argc<2)
    {
        fprintf(stderr,"Usage....\n");
        exit(1);
    }
    printf("%ld\n", mydu(argv[1])/2);
      

    exit(0);
}```

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值