Linux下的C++程序:统计一个目录及其内部文件总共占据的空间大小

来源:互联网 发布:网侠安卓电视直播软件 编辑:程序博客网 时间:2024/06/05 20:09

https://my.oschina.net/Tsybius2014/blog/330628

摘要: Linux下的C++程序:统计一个目录及其内部文件总共占据的空间大小

统计一个目录的大小(byte数),最简单的办法是在控制台输入命令:

du -sb 目录地址

用C++实现这个功能,是通过递归遍历目录下的文件和子目录达到的。需要注意的是,因为Byte数过大,单用一个整型统计Byte的数量,遇到大一些的目录会出现溢出。因此我采用了TB、GB、MB、KB和Byte五个层级来表示目录的大小。

我的代码如下:

#include <stdio.h>#include <sys/stat.h>#include <sys/types.h>#include <unistd.h>#include <stdlib.h>#include <dirent.h>#include <string.h>#define BYTES_OF_CURRENT_FOLDER 4096class CheckSpace{public://构造函数CheckSpace(char *filepath){this -> m_TB = 0;this -> m_GB = 0;this -> m_MB = 0;this -> m_KB = 0;this -> m_Bytes = 0;strcpy(this -> m_FilePath, filepath);Check(filepath); //统计目录中的文件占据的空间大小AddBytes(4096);  //加上该目录本身占据的4096}//获取各项属性int GetTB() return this -> m_TB; }int GetGB() return this -> m_GB; }int GetMB() return this -> m_MB; }int GetKB() return this -> m_KB; }int GetBytes() return this -> m_Bytes; }//展示内容void Display(){printf("查询目录路径 %s\n", m_FilePath);printf("占用空间 %dTB %dGB %dMB %dKB %dByte(s)\n",m_TB, m_GB, m_MB, m_KB, m_Bytes);}private:int m_TB;    //TBint m_GB;    //GBint m_MB;    //MBint m_KB;    //KBint m_Bytes; //Bytechar m_FilePath[128]; //目录地址//Byte数量增加(自动进位)void AddBytes(int bytes){m_Bytes += bytes;while (m_Bytes >= 1024){m_Bytes -= 1024;m_KB++;}while (m_KB >= 1024){m_KB -= 1024;m_MB++;}while (m_MB >= 1024){m_MB -= 1024;m_GB++;}while (m_GB >= 1024){m_GB -= 1024;m_TB++;}}//查看某目录所占空间大小(不含该目录本身的4096Byte)void Check(char *dir){DIR *dp;struct dirent *entry;struct stat statbuf;if ((dp = opendir(dir)) == NULL){fprintf(stderr"Cannot open dir: %s\n", dir);exit(0);}chdir(dir);while ((entry = readdir(dp)) != NULL){lstat(entry -> d_name, &statbuf);if (S_ISDIR(statbuf.st_mode)){if (strcmp(".", entry -> d_name) == 0 ||strcmp("..", entry -> d_name) == 0){continue;}AddBytes(statbuf.st_size);Check(entry -> d_name);}else{AddBytes(statbuf.st_size);}}chdir("..");closedir(dp);}};int main(){char topdir[100] = "/home/oracle/Neeq/Source/";//printf("Directory Scan of Dir: %s\n", topdir);CheckSpace cs = CheckSpace(topdir);cs.Display();//printf("Done.\n");return 0;}

程序运行结果截图如下:

通过计算器可知:

2*1024*1024*1024+933*1024*1024+847*1024+519=3126672903

这个结果与du统计出的结果是一致的


阅读全文
0 0