If I understand your question, and you just want to display a countdown in the same location on the screen, then for terminals that support VT100 emulation (and some earlier VTXX versions), you can just use ANSI escapes to control the cursor visibility and a carriage-return ('\r'
) to return cursor position to the original starting point. If you use the field-width modifier for your integer output, you don't even need the ANSI escape to clear to end-of-line. If you have variable number of characters that are part of your countdown, you can use the ANSI escape to clear to end-of-line to ensure all text is erased each iteration.
For example you could do:
#include <stdio.h>
#include <unistd.h>
int main (void) {
int v = 30;
printf ("\033[?25l"); /* hide cursor */
while (v--) {
printf (" countdown: %2d\r", v); /* print, CR */
fflush (stdout); /* flush stdout */
sleep (1);
}
printf ("\033[?25h\n"); /* restore cursor, \n */
}
If you did have additional text after the countdown number that varied in length with each iteration, you could use:
printf (" countdown: %2d\033[0k\r", v); /* print, clear to end, CR */
which includes the clear to end-of-line escape \033[0k
.
The two additional ANSI escapes used above are \033[?25l
(hide cursor) and \033[?25h
(restore cursor).
The fflush(stdout);
is necessary because output in C is line-buffered by default. Without fflush(stdout);
, all output would be buffered until a '\n'
was encountered -- making all text appear at once.
Give it a try. If you have a VT compatible terminal, it will work fine. But note, the reason ANSI escapes are discouraged is they are not portable. Not all terminals support VT emulation (but a lot do...) See ANSI Escape sequences - VT100 / VT52 for additional escape sequences.
If you are developing a full fledged terminal app with numerous inputs and outputs formatted on the screen, you are better served using a library that provides that capability, such as ncursees etc..