您的位置:首页 > 运维架构 > Linux

Linux 下C编程实现文件夹下文件大小和二级文件夹大小统计

2017-12-29 10:06 2747 查看
时间:2017年12月29日

环境Linux+编译器gcc

问题记录1:

最近在搞统计目录下文件和文件大小的实现,一开始上博客以及上网找相应的demo,找到一些,但大都只是统计当前文件夹下文件的总大小,即没有统计当前文件以及二级文件夹的能力,所以自己弄了一个能够实现当前目录下二级目录的大小统计。

问题记录2:关于stat函数问题

首先还是贴一下stat函数的原型吧,如下。

表头文件:    #include <sys/stat.h>
                   #include <unistd.h>
定义函数:    int stat(const char *file_name, struct stat *buf);
函数说明:    通过文件名filename获取文件信息,并保存在buf所指的结构体stat中
返回值:      执行成功则返回0,失败返回-1,错误代码存于errno

好了,开始说问题了:

使用Linux下stat文件属性函数时,如果你直接把文件名传入stat函数,这时他只会在当前,即程序所在目录下进行查找该文件,如果找不到那么将失败,因此,如果你是想通过这个程序去统计其它文件夹里面的文件,这时需要将那个文件的全路径传给stat函数,这样就不会出错了。

说了这么多贴一下代码,大家一起分享一下吧:

#include <stdio.h> 

#include <dirent.h> 

#include <string.h>

#include <sys/types.h>

#include <stdbool.h>

#include <sys/stat.h> 

void main(int argc,char **argv)

{
int caculatefilesize(char *path,bool ischilddir);
bool ischilddir =false;

if(argc<2)
{
printf("Usage:%s + %s\n",argv[0],argv[1]);
return;
}
caculatefilesize(argv[1],ischilddir);

}

int caculatefilesize(char *path,bool ischilddir)

{
DIR *ptr; 
struct stat buf; 

  struct dirent *dir; 

 
bool childDirflag=false;
char pathname[60];
char pathnametmp[60];

int pathNamelen=sizeof(pathname);

  int total_size=0; 

  int len =0; 

if((ptr = opendir(path))==NULL)
{
printf("Open dir failed!\n");
return -1;
}

strcpy(pathnametmp,path);
strcat(pathnametmp,"/");

for (dir = readdir(ptr); dir != NULL; dir = readdir(ptr)) 
{
if(!strcmp(".",dir->d_name)||!strcmp("..",dir->d_name)) 
continue;
memset(pathname,0,pathNamelen);
strcpy(pathname,pathnametmp);
strcat(pathname,dir->d_name);

if(stat(pathname, &buf)<0)
{
printf("Couldn't stat %s\n", dir->d_name); 
continue;
}

if(S_ISDIR(buf.st_mode))
{
childDirflag =true;
total_size =caculatefilesize(pathname,childDirflag);
printf("the size:%dByte filename:%s\n",total_size,pathname);
continue;
}
if(ischilddir)
{
len = buf.st_size;
total_size +=len;
}
else 
{
len = buf.st_size;
printf("the size:%dByte filename:%s\n",len,dir->d_name); 
}
}
closedir(ptr);
return total_size;

}
以上只是能够查找二级文件夹(二级文件夹下没有下一级文件夹)大小,可继续改进。

over!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐