Last active
September 8, 2015 13:40
-
-
Save Xophmeister/317097c5e2ea1d8d7343 to your computer and use it in GitHub Desktop.
Quick-and-Dirty Human Size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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