#Progress in C
This is in an example meant to present some ideas regarding command-line progress bars in C.
##Important parts
The main idea is to overwrite stdout
with new information every time a particular step is reached. I accomplished this using the VT100 emulator hack from this Stack Overflow answer. In a nutshell, printing ^[[2K
to stdout
erases the current line, but it doesn't necessarily move the cursor to the start. Printing \r
does that. Also, I decided I wanted to print a newline character after the progress indicator, but I need to get rid of that newline on the next print. That's what \b
does: it inserts a backspace, deleting the last character printed.
Also important is the call to fflush
, which will guarantee that the print operation completes and is visible before the program moves on to its next task (see this Stack Overflow answer).
##Less important parts
I decided to let the progress function manage its own progress buffer, which is dynamically allocated on each call to print_progress
. An alternative would be to pass in a buffer that is allocated elsewhere along with a size parameter. Then the print_progress
function would need to make sure not to overrun the buffer.
I also decided to go ahead and print an extra newline character in main
before the first print_progress
call. Otherwise the first \b
printed would delete the newline from the command prompt, which is allowed but not usually expected.
I borrowed a platform-independent my_wait
function from this Stack Overflow answer to test tracking progress with long-running function calls.
Memory allocation is bad for big sizes of tasks and it'll consume a lot of terminal space... A good option is to normalize it to 100...
#define PERCENTAGE(V, T) (100 - (((T - V) * 100) / T))
char *buffer = calloc(100 + prefix_length + suffix_length + 1, 1);
for (; i < 100; ++i)
{
buffer[prefix_length + i] = i < PERCENTAGE(count, max) ? '#' : ' ';
}