#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;
}