ctucx.git: stagit

ctucx' stagit fork

commit abad2b6e02ae04cd6cae1bff5365981bd9bfe8dd
parent f33c53572d55083e67743144e2e3fbd976ed3d8f
Author: Leah (ctucx) <leah@ctu.cx>
Date: Mon, 23 May 2022 18:44:51 +0200

format_bytes: add function to format bytes into human-readable string
1 file changed, 24 insertions(+), 0 deletions(-)
M
stagit.c
|
24
++++++++++++++++++++++++
diff --git a/stagit.c b/stagit.c
@@ -8,6 +8,7 @@
 #include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <math.h>
 #include <string.h>
 #include <time.h>
 #include <unistd.h>

@@ -516,6 +517,29 @@ printtimeshort(FILE *fp, const git_time *intime)
 	fputs(out, fp);
 }
 
+static const char
+*format_bytes(uint64_t bytes)
+{
+	char *suffix[] = {"B", "KB", "MB", "GB", "TB"};
+	char length = sizeof(suffix) / sizeof(suffix[0]);
+
+	int i = 0;
+	double dblBytes = bytes;
+
+	if (bytes > 1024) {
+		for (i = 0; (bytes / 1024) > 0 && i<length-1; i++, bytes /= 1024)
+			dblBytes = bytes / 1024.0;
+	}
+
+	static char output[200];
+	if (fmod(dblBytes, 1) != 0) {
+		sprintf(output, "%.02lf %s", dblBytes, suffix[i]);
+	} else {
+		sprintf(output, "%.0lf %s", dblBytes, suffix[i]);
+	}
+	return output;
+}
+
 void
 writeheader(FILE *fp, const char *title)
 {