I have always thought it was cool when a program like wget would show you ‘visually’ on a command console how much longer a file would take to download, essentially an ASCII progress bar. The message was ASCII graphics really, and would have some movement to it – I always wondered how you could achieve this using standard out and some simple fprintf commands to modify the text in place. There are a few ways you can achieve some graphics on the console.
- You can utilize the ncurses library.
- You can utilize fprintf and the \b (backspace) character to replace some text.
The advantage of ncurses is it can re-draw and clear the entire screen, draw certain aspects of the screen at different points. There is a predefined API for ncurses and is far more powerful than simple fprintf work. Even the common ‘make menuconfig’ directives utilize the ncurses library.
Using the second method is a little mickey mouse but still fun none-the-less. I wrote a little program that will visually give you progress by swapping textual values within two square opening and closing brackets. In this case [w] and [e].
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
fprintf(stdout, "Writing from a to b ....");
fprintf(stdout, " [ ]");
for (;;) {
fprintf(stdout, "\b\b\b ");
fprintf(stdout, "\b\b\b[e]");
usleep(500000);
fprintf(stdout, "\b\b\b[w]");
usleep(500000);
}
return 0;
}
Initially the code writes out the standard line. Then the second fprintf outputs the [ ], then the first line in the ‘for’ loop backspaces three characters, this includes the opening and closing square brackets. The following lines will pause for half a second, remove the [ ] then populate them with the ‘[e]‘ or the ‘[w]‘. This is merely a trick of backspacing at such a rate in which your eyes do not notice.
What cool things have you seen done in a terminal?