How do you determine the amount of Linux system RAM in C++?

前端 未结 4 1609
迷失自我
迷失自我 2020-12-04 17:54

I just wrote the following C++ function to programatically determine how much RAM a system has installed. It works, but it seems to me that there should be a simpler way to

4条回答
  •  余生分开走
    2020-12-04 18:41

    There's no need to use popen(), you can just read the file yourself. Also, if there first line isn't what you're looking for, you'll fail, since head -n1 only reads the first line and then exits. I'm not sure why you're mixing C and C++ I/O like that; it's perfectly OK, but you should probably opt to go all C or all C++. I'd probably do it something like this:

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

提交回复
热议问题