The memory usage information of the system can be found in the virtual file system/proc/meminfo,
So just open the/proc/meminfo file and read the information from it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#define Mem_part "/proc/meminfo"
The structure used to store memory information
struct MEM_INFO
{
Char memtotal[20];
Char memfree[20];
Char memavailable[20];
Char buffers[20];
Char cached[20];
};
typedef struct MEM_INFO Mem_info,*pmem_info;
Opens the file specified by filename, from which to read the linenumber line
Return value: Successfully returned 1, failed to return 0
int Get_file_line (char *result,char *filename,int linenumber)
{
FILE *filepointer;
int i=0;
Char Buffer[filebuffer_length];
if ((filename==null) | | | (Result==null))
{
return 0;
}
if (! ( Filepointer=fopen (FileName, "RB")))
{return 0;}
while ((!feof (Filepointer)) && (I<linenumber))
{
if (!fgets (Buffer,filebuffer_length,filepointer))
{
return 0;
}
i++;//almost forgot to add this sentence again.
}
/* printf ("\n%d\n", sizeof (*result));
if (strlen (buffer) >sizeof (*result))//Can not write this, although Fgets read a line will be added to the end of ' ", but sizeof (result) results are the size of the type of result itself, So I can't count that. When a static array is passed into a function, it is only known inside the function that it is a pointer
{
return 0;
}*/
strcpy (Result,buffer);
if (0!=fclose (Filepointer))
{
return 0;
}
return 1;
}
Read the information in the/proc/meminfo by line and save it in the mem struct
int Get_mem_info (Pmem_info mem)
{
Char buffer[300];
if (NULL==MEM)
{
printf ("\nget_mem_info:param null!\n");
return 0;
}
memset (mem,0,sizeof (mem_info));
if (1==get_file_line (buffer,mem_part,1))//Read First line
{
SSCANF (buffer, "%*s%s", mem->memtotal);
if (1==get_file_line (buffer,mem_part,2))//Read second line
{sscanf (buffer, "%*s%s", mem->memfree);
if (1==get_file_line (buffer,mem_part,3))//Read Third line
{sscanf (buffer, "%*s%s", mem->memavailable);
if (1==get_file_line (buffer,mem_part,4))//Read line Fourth
{sscanf (buffer, "%*s%s", mem->buffers);
if (1==get_file_line (buffer,mem_part,5))//Read line fifth
{
SSCANF (buffer, "%*s%s", mem->cached);
return 1;
}
}
}
}
}
return 0;
}
int main ()
{
Mem_info Mem;
Get_mem_info (&MEM);
printf ("\n%s%s%s%s%s\n", Mem.) Memtotal,mem. Memfree,mem. Memavailable,mem. Buffers,mem. Cached);
return 1;
}
Linux c Read system memory usage information