计算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;  
}

 

posted @ 2024-03-31 09:20  He_LiangLiang  阅读(12)  评论(0编辑  收藏  举报