Reputation: 25
This is what I currently have but I'm doing it wrong. Can someone please explain how to format the output into GB? I have a total of 16GB of available ram and I'm getting an output of 62GB.
#include <stdio.h>
#include <sys/sysinfo.h>
int main(void) {
struct sysinfo sys_info; // for system information
sysinfo(&sys_info); // to get system information
printf("Total usable memory size: %ldGB", sys_info.totalram / 1024 / 1024 / 1024);
return 0;
}
Upvotes: 0
Views: 382
Reputation: 38
First note that sysinfo
will actually already give you the size in kB (KiloBytes). That means that you actually divide by 1000.0
to get GB (GigaByte). Also I think you would want your output to be double precision.
I modified your code
#include <stdio.h>
#include <sys/sysinfo.h>
int main(void) {
struct sysinfo sys_info; // for system information
sysinfo(&sys_info); // to get system information
// note: %.3f is double precision but I only need to display 3 decimal places
printf("Total usable memory size : %.3fGB", sys_info.totalram / 1000.0 / 1000.0 / 1000.0);
return 0;
}
Don't be confused when you try to verify this using cat /proc/meminfo
. This is actually displaying the total memory in KibiBytes. One KibiByte is 1.024 KiloByte. You can do the math and it will also end up in the same solution.
Upvotes: 1