From f975594e55bdc05ee436bc7bdcd6e09aec5357b1 Mon Sep 17 00:00:00 2001 From: Joel Kronqvist Date: Sun, 7 Apr 2024 10:53:40 +0300 Subject: Finished implementation for formatting for human readability --- stdu.c | 49 ++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) (limited to 'stdu.c') diff --git a/stdu.c b/stdu.c index f7f5511..f2273f7 100644 --- a/stdu.c +++ b/stdu.c @@ -6,6 +6,7 @@ #include #include "intmath.h" +#include "formatting.h" #include "config-parser.h" int tests_run = 0; @@ -24,7 +25,6 @@ int main (int argc, char* argv[]) { } Config* conf = (Config*) res.result; - if (conf->human_readable) printf("human readable\n"); unsigned int base = 10; if (conf->human_readable && conf->precision == 0) { @@ -48,10 +48,52 @@ int main (int argc, char* argv[]) { char* buf = malloc(bufsize); char* tmpbuf; + size_t stdout_buffer_size = 16; + char* stdout_buffer = malloc(stdout_buffer_size); + int previous_line_strlen = 0; + while (1) { /* output */ - printf("\r%u", bytes_read); - if (fflush(stdin) == EOF) { + if (conf->human_readable && base == 10) { + int res = int_floored_with_prefix( + &stdout_buffer, + &stdout_buffer_size, + bytes_read, + conf->precision + ); + if (res < 0) { + printf("\r%u \ + (error when getting prefix)", + bytes_read); + continue; + } + printf( + "\r%*sB", + previous_line_strlen, + stdout_buffer + ); + previous_line_strlen + = int_max(res, previous_line_strlen); + } else if (conf->human_readable && base == 1024) { + int success = int_floored_with_binary_prefix( + &stdout_buffer, + &stdout_buffer_size, + bytes_read + ); + if (success < 0) { + printf("\r%u \ + (error when getting prefix)", + bytes_read); + } + printf( + "\r%*sB", + 4 + (bytes_read > 1024), + stdout_buffer + ); + } else { + printf("\r%u", bytes_read); + } + if (fflush(stdout) == EOF) { printf("\n"); perror("error during fflush"); return 1; @@ -96,6 +138,7 @@ int main (int argc, char* argv[]) { } } printf("\n"); + free(stdout_buffer); return 0; } -- cgit v1.2.3