]> git.sur5r.net Git - i3/i3status/blob - src/print_disk_info.c
FreeBSD: fix disk usage print
[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 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
10 #include <sys/param.h>
11 #include <sys/mount.h>
12 #endif
13
14
15 #include "i3status.h"
16
17 #define TERABYTE (1024ULL * 1024 * 1024 * 1024)
18 #define GIGABYTE (1024ULL * 1024 * 1024)
19 #define MEGABYTE (1024ULL * 1024)
20 #define KILOBYTE (1024ULL)
21
22 /*
23  * Prints the given amount of bytes in a human readable manner.
24  *
25  */
26 static void print_bytes_human(uint64_t bytes) {
27         if (bytes > TERABYTE)
28                 printf("%.02f TB", (double)bytes / TERABYTE);
29         else if (bytes > GIGABYTE)
30                 printf("%.01f GB", (double)bytes / GIGABYTE);
31         else if (bytes > MEGABYTE)
32                 printf("%.01f MB", (double)bytes / MEGABYTE);
33         else if (bytes > KILOBYTE)
34                 printf("%.01f KB", (double)bytes / KILOBYTE);
35         else {
36                 printf("%.01f B", (double)bytes);
37         }
38 }
39
40 /*
41  * Does a statvfs and prints either free, used or total amounts of bytes in a
42  * human readable manner.
43  *
44  */
45 void print_disk_info(const char *path, const char *format) {
46         const char *walk;
47
48 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
49         struct statfs buf;
50
51         if (statfs(path, &buf) == -1)
52                 return;
53 #else
54         struct statvfs buf;
55
56         if (statvfs(path, &buf) == -1)
57                 return;
58 #endif
59
60         for (walk = format; *walk != '\0'; walk++) {
61                 if (*walk != '%') {
62                         putchar(*walk);
63                         continue;
64                 }
65
66                 if (BEGINS_WITH(walk+1, "free")) {
67                         print_bytes_human((uint64_t)buf.f_bsize * (uint64_t)buf.f_bfree);
68                         walk += strlen("free");
69                 }
70
71                 if (BEGINS_WITH(walk+1, "used")) {
72                         print_bytes_human((uint64_t)buf.f_bsize * ((uint64_t)buf.f_blocks - (uint64_t)buf.f_bfree));
73                         walk += strlen("used");
74                 }
75
76                 if (BEGINS_WITH(walk+1, "total")) {
77                         print_bytes_human((uint64_t)buf.f_bsize * (uint64_t)buf.f_blocks);
78                         walk += strlen("total");
79                 }
80
81                 if (BEGINS_WITH(walk+1, "avail")) {
82                         print_bytes_human((uint64_t)buf.f_bsize * (uint64_t)buf.f_bavail);
83                         walk += strlen("avail");
84                 }
85         }
86 }