我刚编写了以下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;
}
Run Code Online (Sandbox Code Playgroud)
首先,我popen("head -n1 /proc/meminfo")用来从系统中获取meminfo文件的第一行.该命令的输出看起来像
MemTotal:775280 kB
一旦我得到了输出istringstream,就很容易将它标记为获取我想要的信息.我的问题是,是否有更简单的方法来读取此命令的输出?是否有标准的C++库调用来读取系统RAM的数量?
Joh*_*itb 68
在Linux上,您可以使用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 */
};
Run Code Online (Sandbox Code Playgroud)
如果你想单独使用C++的功能(我会坚持sysinfo),我建议使用std::ifstream和使用C++方法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
}
Run Code Online (Sandbox Code Playgroud)
没有任何必要使用popen()。您可以自己阅读该文件。
另外,如果它们的第一行不是您要查找的内容,您将失败,因为head -n1只读取第一行然后退出。我不知道为什么你要这样混合 C 和 C++ I/O;完全没问题,但您可能应该选择全部使用 C 或全部 C++。我可能会这样做:
int GetRamInKB(void)
{
FILE *meminfo = fopen("/proc/meminfo", "r");
if(meminfo == NULL)
... // handle error
char line[256];
while(fgets(line, sizeof(line), meminfo))
{
int ram;
if(sscanf(line, "MemTotal: %d kB", &ram) == 1)
{
fclose(meminfo);
return ram;
}
}
// If we got here, then we couldn't find the proper line in the meminfo file:
// do something appropriate like return an error code, throw an exception, etc.
fclose(meminfo);
return -1;
}
Run Code Online (Sandbox Code Playgroud)