目录大小

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

岁酱吖の 提交于 2020-03-01 03:27:29
统计一个目录的大小(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 4096 class 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); /