commit e0ac7dc8bc2388ea3e32c018353c6340b552e86d
parent f86b88c00a16af75bdde3c11028b44cfd155f9c9
Author: Wim Dupont <wim@wimdupont.com>
Date: Fri, 25 Apr 2025 19:25:26 +0200
file size to readable format
Diffstat:
M | cex.c | | | 24 | ++++++++++++++++++++++-- |
1 file changed, 22 insertions(+), 2 deletions(-)
diff --git a/cex.c b/cex.c
@@ -99,6 +99,7 @@ static void make_open_default(void);
static void make_mime_default(const char *mime, const char *app);
static int rm_file(const char *fname);
static int rename_file(const char *fname);
+static char *human_readable_bytes(char *buf, intmax_t bytes, bool decimal);
static char *prompt_answer(char *buf, size_t size, const char *question);
static char *cpstr(char *dest, const char *src);
static char *get_file_info(char *buf, const char *filepath);
@@ -676,6 +677,7 @@ get_file_info(char *buf, const char *filepath)
struct tm *tm;
struct group *grp;
char mods[11], datestr[256], modfill = '-';
+ char hrbytes[200];
if ((stat(filepath, &statbuf)) != 0) {
switch (errno) {
@@ -713,11 +715,11 @@ get_file_info(char *buf, const char *filepath)
tm = localtime(&statbuf.st_mtime);
strftime(datestr, sizeof(datestr), nl_langinfo(D_T_FMT), tm);
- sprintf(buf, "%10.10s %s %s %9jd %s",
+ sprintf(buf, "%10.10s %s %s %s %s",
mods,
usr->pw_name,
grp->gr_name,
- (intmax_t)statbuf.st_size,
+ human_readable_bytes(hrbytes, (intmax_t)statbuf.st_size, TRUE),
datestr);
return buf;
@@ -1191,6 +1193,24 @@ is_dir(DirWin *dirwin, size_t index)
}
char *
+human_readable_bytes(char *buf, intmax_t bytes, bool decimal)
+{
+ double dblBytes = bytes;
+ int power = decimal ? 1000 : 1024;
+ char *suffix[] = {"B", "KB", "MB", "GB", "TB"};
+ char length = sizeof(suffix) / sizeof(suffix[0]);
+ int i = 0;
+
+ if (bytes > power)
+ for (i = 0; (bytes / power) > 0 && i<length-1; i++, bytes /= 1000)
+ dblBytes = bytes / (double) power;
+
+ sprintf(buf, "%.02lf%s", dblBytes, suffix[i]);
+
+ return buf;
+}
+
+char *
prompt_answer(char *buf, size_t size, const char *question)
{
move(maxy-1, 0);