Skip to content

Instantly share code, notes, and snippets.

@Xophmeister
Last active September 8, 2015 13:40
Show Gist options
  • Save Xophmeister/317097c5e2ea1d8d7343 to your computer and use it in GitHub Desktop.
Save Xophmeister/317097c5e2ea1d8d7343 to your computer and use it in GitHub Desktop.
Quick-and-Dirty Human Size
#include <stdio.h>
#include <sys/types.h>
/**
@brief Human file size
@param size File size in bytes
@return Base 2 prefixed file size string
This isn't as complete as Gnulib's `human_readable`, but it does the
job without any allocation or messing around
*/
const char* human_size(ssize_t size) {
static char prefix[8] = {'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'};
static char output[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
if (size < 0) {
(void)snprintf(output, 10, "Error");
} else {
double quant = (double)size;
ssize_t i = -1;
while (quant >= 1024.0) {
quant /= 1024.0;
++i;
}
if (i < 0 || i > 7) {
(void)snprintf(output, sizeof(output), "%ld B", size);
} else {
(void)snprintf(output, sizeof(output), "%.1f %ciB", quant, prefix[i]);
}
}
return output;
}
#ifndef _HUMAN_SIZE_H
#define _HUMAN_SIZE_H
#include <sys/types.h>
const char* human_size(ssize_t);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment