Linux C++獲取磁盤剩余空間和可用空間


完整源碼


#include <sys/statfs.h>
#include <string>
#include <iostream>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

/// get executable path
std::string get_cur_executable_path_()
{
    char *p                 = NULL;

    const int len           = 256;
    /// to keep the absolute path of executable's path
    char arr_tmp[len]       = {0};

    int n                   = readlink("/proc/self/exe", arr_tmp, len);
    if (NULL                != (p = strrchr(arr_tmp,'/')))
        *p = '\0';
    else
    {
        printf("wrong process path");
        std::string("");
    }

    return std::string(arr_tmp);
}
 
int main(int argc, char* argv[], char *env[])
{
    /// 讀取executable所在絕對路徑
    std::string exec_str    = get_cur_executable_path_();
    std::cout << "str=" << exec_str << "\n\n";

    /// 用於獲取磁盤剩余空間
	struct statfs diskInfo;
	statfs(exec_str.c_str(), &diskInfo);

	unsigned long long blocksize                = diskInfo.f_bsize;	//每個block里包含的字節數
	unsigned long long totalsize                = blocksize * diskInfo.f_blocks; 	//總的字節數,f_blocks為block的數目

	printf("Total_size = %llu B                 = %llu KB = %llu MB = %llu GB\n", 
		                                            totalsize, totalsize>>10, totalsize>>20, totalsize>>30);
	
	unsigned long long freeDisk                 = diskInfo.f_bfree * blocksize;	//剩余空間的大小
	unsigned long long availableDisk            = diskInfo.f_bavail * blocksize; 	//可用空間大小
	printf("Disk_free = %llu MB                 = %llu GB\nDisk_available = %llu MB = %llu GB\n", 
		                                            freeDisk>>20, freeDisk>>30, availableDisk>>20, availableDisk>>30);
	return 0;

}

輸出結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM