s2dblocks

[archived] statusbar blocks for dwm
git clone https://hhvn.uk/s2dblocks
git clone git://hhvn.uk/s2dblocks
Log | Files | Refs

mem.c (1152B)


      1 #include <stdio.h>
      2 #include <ctype.h>
      3 #include <string.h>
      4 #include <stdlib.h>
      5 #include "status2d.h"
      6 
      7 #define CONSTLEN(str) ((size_t)((sizeof(str) - sizeof(str[0])) / sizeof(str[0])))
      8 
      9 int
     10 main(void) {
     11 	long double total = 0, used = 0, percent = 0;
     12 #ifdef __linux__
     13 	long double avail = 0;
     14 	char buf[1024], *p;
     15 	FILE *f;
     16 
     17 	if (!(f = fopen("/proc/meminfo", "r"))) {
     18 		perror("fopen()");
     19 		return 1;
     20 	}
     21 
     22 	while (fgets(buf, sizeof(buf), f) && (!avail || !total)) {
     23 		for (p = buf; !isdigit(*p) && *p; p++);
     24 		if (strncmp(buf, "MemTotal:", CONSTLEN("MemTotal:")) == 0) {
     25 			total = strtold(p, NULL);
     26 		} else if (strncmp(buf, "MemAvailable:", CONSTLEN("MemAvailable:")) == 0) {
     27 			avail = strtold(p, NULL);
     28 		}
     29 	}
     30 	fclose(f);
     31 
     32 	used = total - avail;
     33 #else
     34 	s2d_print("no handler for this OS");
     35 	s2d_finish();
     36 #endif
     37 	percent = (used / total) * 100;
     38 	s2d_bg(BRBG);
     39 	if (percent >= 75)
     40 		s2d_fg(RED);
     41 	else if (percent >= 60)
     42 		s2d_fg(ORANGE);
     43 	else if (percent >= 50)
     44 		s2d_fg(YELLOW);
     45 	else
     46 		s2d_fg(GREEN);
     47 	s2d_bar(0, 2, 3, bar_height - 4, 1, percent);
     48 	s2d_reset(0, 1);
     49 	s2d_forward(-1);
     50 	s2d_forward(2);
     51 	s2d_print("%.0LF%%", percent);
     52 	s2d_finish();
     53 }