From 10d81574774acb4d00ae9b9feef9c30e6d0b6c78 Mon Sep 17 00:00:00 2001 From: Jan Vidar Krey Date: Tue, 2 Oct 2012 23:01:57 +0200 Subject: [PATCH] Added a utility function to convert an arbitrary byte size into a human readable string. E.g. 849484 becomes "829.57 KB". --- src/util/misc.c | 17 +++++++++++++++++ src/util/misc.h | 13 +++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/util/misc.c b/src/util/misc.c index e3a809a..1fe5c9a 100644 --- a/src/util/misc.c +++ b/src/util/misc.c @@ -305,6 +305,23 @@ int is_number(const char* value, int* num) } +const char* format_size(size_t bytes, char* buf, size_t bufsize) +{ + static const char* quant[] = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; + size_t b = bytes; + size_t factor = 0; + size_t divisor = 1; + while (b > 1024) + { + factor++; + b = (b >> 10); + divisor = (divisor << 10); + } + snprintf(buf, bufsize, "%.2f %s", (double) bytes / (double) divisor, quant[factor]); + return buf; +} + + const char* uhub_itoa(int val) { static char buf[22]; diff --git a/src/util/misc.h b/src/util/misc.h index 9526d0d..9841c7f 100644 --- a/src/util/misc.h +++ b/src/util/misc.h @@ -42,6 +42,19 @@ extern char* strip_off_quotes(char* line); */ extern int is_number(const char* str, int* num); +/** + * Convert the 'bytes' number into a formatted byte size string. + * E.g. "129012" becomes "125.99 KB". + * Note, if the output buffer is not large enough then the output + * will be truncated. The buffer will always be \0 terminated. + * + * @param bytes the number that should be formatted. + * @param[out] buf the buffer the string should be formatted into + * @param bufsize the size of 'buf' + * @return A pointer to buf. + */ +extern const char* format_size(size_t bytes, char* buf, size_t bufsize); + extern int file_read_lines(const char* file, void* data, file_line_handler_t handler); /**