我刚刚编写了以下C ++函数,以编程方式确定系统已安装了多少RAM。它有效,但是在我看来,应该有一种更简单的方法来执行此操作。有人可以告诉我我是否想念东西吗?
getRAM() { FILE* stream = popen( "head -n1 /proc/meminfo", "r" ); std::ostringstream output; int bufsize = 128; while( !feof( stream ) && !ferror( stream )) { char buf[bufsize]; int bytesRead = fread( buf, 1, bufsize, stream ); output.write( buf, bytesRead ); } std::string result = output.str(); std::string label, ram; std::istringstream iss(result); iss >> label; iss >> ram; return ram; }
首先,我popen("head -n1 /proc/meminfo")要从系统中获取meminfo文件的第一行。该命令的输出看起来像
popen("head -n1 /proc/meminfo")
内存总量:775280 kB
一旦在中获得了输出istringstream,就可以对它进行标记化以获取所需的信息,这很简单。我的问题是,有没有更简单的方法可以读取此命令的输出?是否有标准的C ++库调用来读取系统RAM的数量?
istringstream
在Linux上,您可以使用sysinfo在以下结构中设置值的函数:
sysinfo
#include <sys/sysinfo.h> int sysinfo(struct sysinfo *info); struct sysinfo { long uptime; /* Seconds since boot */ unsigned long loads[3]; /* 1, 5, and 15 minute load averages */ unsigned long totalram; /* Total usable main memory size */ unsigned long freeram; /* Available memory size */ unsigned long sharedram; /* Amount of shared memory */ unsigned long bufferram; /* Memory used by buffers */ unsigned long totalswap; /* Total swap space size */ unsigned long freeswap; /* swap space still available */ unsigned short procs; /* Number of current processes */ unsigned long totalhigh; /* Total high memory size */ unsigned long freehigh; /* Available high memory size */ unsigned int mem_unit; /* Memory unit size in bytes */ char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */ };
如果您只想使用C 函数来做到这一点(我会坚持使用sysinfo),建议您使用std::ifstream和采取C 方法std::string:
std::ifstream
std::string
unsigned long get_mem_total() { std::string token; std::ifstream file("/proc/meminfo"); while(file >> token) { if(token == "MemTotal:") { unsigned long mem; if(file >> mem) { return mem; } else { return 0; } } // ignore rest of the line file.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } return 0; // nothing found }