]> git.sur5r.net Git - i3/i3status/blob - src/print_disk_info.c
disk_info: implement %avail
[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 /*
18  * Prints the given amount of bytes in a human readable manner.
19  *
20  */
21 static void print_bytes_human(uint64_t bytes) {
22         if (bytes > TERABYTE)
23                 printf("%.02f TB", (double)bytes / TERABYTE);
24         else if (bytes > GIGABYTE)
25                 printf("%.01f GB", (double)bytes / GIGABYTE);
26         else if (bytes > MEGABYTE)
27                 printf("%.01f MB", (double)bytes / MEGABYTE);
28         else if (bytes > KILOBYTE)
29                 printf("%.01f KB", (double)bytes / KILOBYTE);
30         else {
31                 printf("%.01f B", (double)bytes);
32         }
33 }
34
35 /*
36  * Does a statvfs and prints either free, used or total amounts of bytes in a
37  * human readable manner.
38  *
39  */
40 void print_disk_info(const char *path, const char *format) {
41         const char *walk;
42         struct statvfs buf;
43
44         if (statvfs(path, &buf) == -1)
45                 return;
46
47         for (walk = format; *walk != '\0'; walk++) {
48                 if (*walk != '%') {
49                         putchar(*walk);
50                         continue;
51                 }
52
53                 if (BEGINS_WITH(walk+1, "free")) {
54                         print_bytes_human((uint64_t)buf.f_bsize * (uint64_t)buf.f_bfree);
55                         walk += strlen("free");
56                 }
57
58                 if (BEGINS_WITH(walk+1, "used")) {
59                         print_bytes_human((uint64_t)buf.f_bsize * ((uint64_t)buf.f_blocks - (uint64_t)buf.f_bfree));
60                         walk += strlen("used");
61                 }
62
63                 if (BEGINS_WITH(walk+1, "total")) {
64                         print_bytes_human((uint64_t)buf.f_bsize * (uint64_t)buf.f_blocks);
65                         walk += strlen("total");
66                 }
67
68                 if (BEGINS_WITH(walk+1, "avail")) {
69                         print_bytes_human((uint64_t)buf.f_bsize * (uint64_t)buf.f_bavail);
70                         walk += strlen("avail");
71                 }
72         }
73 }