計算linux磁盤空間

 

可以準確獲取某個掛載點的硬盤空間,已使用空間。

現在問題就出在 掛載點的判斷 和類型過濾上面。

 

#include <iostream>  
#include <fstream>  
#include <sstream>  
#include <vector>  
#include <string>  
#include <sys/statvfs.h>  
#include <map>

struct  DISK_INFO{
    unsigned long long diskTotal;
    unsigned long long diskUsed;
};  

void checkDiskForMountPoint(const std::string& mountPoint, std::map<std::string, DISK_INFO>& mapDiskInfo) {  
    struct statvfs stats;  
    if (statvfs(mountPoint.c_str(), &stats) != 0) {  
        std::cerr << "Error getting disk usage for " << mountPoint << std::endl;  
        return;  
    }  
  
    unsigned long long totalBytes = static_cast<unsigned long long>(stats.f_blocks) * static_cast<unsigned long long>(stats.f_bsize);  
    unsigned long long usedBytes = (static_cast<unsigned long long>(stats.f_blocks - stats.f_bfree) * static_cast<unsigned long long>(stats.f_bsize));  
    mapDiskInfo[mountPoint] = {0};
    mapDiskInfo[mountPoint].diskTotal = totalBytes/(1024 * 1024);
    mapDiskInfo[mountPoint].diskUsed = usedBytes/(1024 * 1024);
}  
  
void checkAllDisks() {  
    std::ifstream mountsFile("/proc/mounts");  
    std::string line;  

    std::map<std::string, DISK_INFO> mapDiskInfo;
  
    while (std::getline(mountsFile, line)) {  
        std::istringstream iss(line);  
        std::string fsType, mountPoint, options;  
        if (!(iss >> fsType >> mountPoint >> options)) {  
            continue; // Skip invalid lines  
        }  
  
        //todo: 還要考慮 docker 的那種掛在情況
        //todo: 需要在 網關盒子上真實的跑一下 
        // Filter out entries that are not real file systems or are not mounted to a directory  
        if (fsType == "none" || fsType == "tmpfs" || "devtmpfs"== fsType || mountPoint.find('/') == std::string::npos) {  
            continue;  
        }
  
        checkDiskForMountPoint(mountPoint,mapDiskInfo);  
    }  

    for(auto it=mapDiskInfo.begin(); it!= mapDiskInfo.end(); ++it){
        if(it->second.diskTotal>0){
            std::cout<<"Mount Point:"<<it->first<<",diskTotal:"<<it->second.diskTotal<<"Mb,diskUsed:"<<it->second.diskUsed<<"Mb"<<std::endl;
        }
    }
}  
  
int main() {  
    checkAllDisks();  
    return 0;  
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章