]> git.sur5r.net Git - i3/i3status/blob - src/print_disk_info.c
Implement disk info (%free/%used/%total)
[i3/i3status] / src / print_disk_info.c
1 // vim:ts=8:expandtab
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <ctype.h>
6 #include <stdint.h>
7 #include <sys/statvfs.h>
8 #include <sys/types.h>
9
10 #include "i3status.h"
11
12 #define TERABYTE (1024ULL * 1024 * 1024 * 1024)
13 #define GIGABYTE (1024ULL * 1024 * 1024)
14 #define MEGABYTE (1024ULL * 1024)
15 #define KILOBYTE (1024ULL)
16
17 void print_bytes_human(uint64_t bytes) {
18         /* 1 TB */
19         if (bytes > TERABYTE)
20                 printf("%f TB", (double)bytes / TERABYTE);
21         else if (bytes > GIGABYTE)
22                 printf("%.01f GB", (double)bytes / GIGABYTE);
23         else if (bytes > MEGABYTE)
24                 printf("%.01f MB", (double)bytes / MEGABYTE);
25         else if (bytes > KILOBYTE)
26                 printf("%.01f KB", (double)bytes / KILOBYTE);
27         else {
28                 printf("%.01f B", (double)bytes);
29         }
30
31 }
32
33 /*
34  * Just parses /proc/net/wireless looking for lines beginning with
35  * wlan_interface, extracting the quality of the link and adding the
36  * current IP address of wlan_interface.
37  *
38  */
39 void print_disk_info(const char *path, const char *format) {
40         const char *walk;
41         struct statvfs buf;
42
43         if (statvfs(path, &buf) == -1)
44                 return;
45
46         for (walk = format; *walk != '\0'; walk++) {
47                 if (*walk != '%') {
48                         putchar(*walk);
49                         continue;
50                 }
51
52                 if (BEGINS_WITH(walk+1, "free")) {
53                         print_bytes_human(buf.f_bsize * buf.f_bfree);
54                         walk += strlen("free");
55                 }
56
57                 if (BEGINS_WITH(walk+1, "used")) {
58                         print_bytes_human(buf.f_bsize * (buf.f_blocks - buf.f_bfree));
59                         walk += strlen("used");
60                 }
61
62                 if (BEGINS_WITH(walk+1, "total")) {
63                         print_bytes_human(buf.f_bsize * buf.f_blocks);
64                         walk += strlen("total");
65                 }
66         }
67 }