micro-utils/include/libmu/human.h

31 lines
500 B
C
Raw Permalink Normal View History

2023-11-21 19:18:42 +00:00
#ifndef _HUMAN_H
#define _HUMAN_H
2024-03-13 19:23:46 +00:00
#include <stdlib.h>
#include <stdint.h>
2024-02-21 09:12:37 +00:00
#define MU_HUMAN_BUF_SIZE 16
char *mu_humansize(off_t n, off_t block) {
static char buf[MU_HUMAN_BUF_SIZE + 1];
2024-03-13 19:23:46 +00:00
memset(buf, '\0', sizeof(buf));
2023-11-21 19:18:42 +00:00
char *postfixes = "BKMGTPE";
double size = n;
size_t i;
2024-03-17 21:46:58 +00:00
2024-02-21 09:12:37 +00:00
for (i = 0; i < strlen(postfixes) && size >= block; i++)
size /= block;
2023-11-21 19:18:42 +00:00
if (i)
snprintf(buf, sizeof(buf), "%.1f%c", size, postfixes[i]);
else
2024-03-27 19:04:17 +00:00
snprintf(buf, sizeof(buf), "%ju", n);
2023-11-21 19:18:42 +00:00
return buf;
}
#endif