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; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?