Linux下的C++程序:統計一個目錄及其內部文件總共佔據的空間大小

統計一個目錄的大小(byte數),最簡單的辦法是在控制檯輸入命令:shell

du -sb 目錄地址

用C++實現這個功能,是經過遞歸遍歷目錄下的文件和子目錄達到的。須要注意的是,由於Byte數過大,單用一個整型統計Byte的數量,遇到大一些的目錄會出現溢出。所以我採用了TB、GB、MB、KB和Byte五個層級來表示目錄的大小。oracle

個人代碼以下:
函數

#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);  //加上該目錄自己佔據的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;    //TB
	int m_GB;    //GB
	int m_MB;    //MB
	int m_KB;    //KB
	int m_Bytes; //Byte
	char 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;
}

程序運行結果截圖以下:this

經過計算器可知:spa

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

這個結果與du統計出的結果是一致的遞歸

ENDstring

相關文章
相關標籤/搜索