C++獲取硬盤大小,內存大小,已使用內存大小,swap內存大小

 

 

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


//物理硬盤  近似ok

// 內存      OK
// 虛擬內存  OK

// cpu     


// 定義一個函數,從文件中讀取內存信息並填充到一個 map 中  
void readMemInfo() {
    const std::string filePath = "/proc/meminfo";
    std::unordered_map<std::string, std::string> memInfo;
    std::ifstream file(filePath);  
    if (!file.is_open()) {  
        std::cerr << "Failed to open file: " << filePath << std::endl;  
        return;  
    }    
    std::string line;  
    while (std::getline(file, line)) {  
        std::size_t pos = line.find(':');  
        if (pos != std::string::npos) {  
            std::string key = line.substr(0, pos);  
            std::string value = line.substr(pos + 1);  
            // 去除兩邊的空白字符  
            memInfo[key] = value.substr(value.find_first_not_of(" \t"),  
                                         value.find_last_not_of(" \t\r\n") - value.find_first_not_of(" \t") + 1);  
        }  
    }  
    file.close();  
    std::size_t pos1 = memInfo["MemTotal"].find(' ');
    std::string memTotalValue = memInfo["MemTotal"].substr(0,pos1);
    std::size_t pos2 = memInfo["MemFree"].find(' ');
    std::string memFreeValue = memInfo["MemFree"].substr(0,pos2);
    std::size_t pos3 = memInfo["SwapTotal"].find(' ');
    std::string swapTotalValue = memInfo["SwapTotal"].substr(0,pos3);
    std::size_t pos4 = memInfo["SwapFree"].find(' ');
    std::string swapFreeValue = memInfo["SwapFree"].substr(0,pos4);
    std::cout<<"MemTotal:"<< memTotalValue <<std::endl; //內存總大小,單位是kb
    std::cout<<"MemFree:"<< memFreeValue <<std::endl;   //內存剩餘大小,單位是kb
    std::cout<<"SwapTotal:"<< swapTotalValue <<std::endl;   // 虛擬內存大小
    std::cout<<"SwapFree:"<< swapFreeValue <<std::endl;   // 虛擬內存大小
}  
  


void checkDisk(){
std::string mountPoint = "/"; // 你可以根據需要修改掛載點  
struct statvfs stats;  
    if (statvfs(mountPoint.c_str(), &stats) != 0) {  
        std::cerr << "Error getting disk usage for " << mountPoint << std::endl; 
    }  

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));  



std::cout << "Total disk size: " << totalBytes / (1024 * 1024) << " MB" << std::endl;  
std::cout << "Used disk size: " << usedBytes / (1024 * 1024) << " MB" << std::endl;  
}  

int main() {  
    readMemInfo();  



    return 0;  
}

 

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