Question

How to update a printed message in terminal without reprinting

I want to make a progress bar for my terminal application that would work something like:

 [XXXXXXX       ] 

which would give a visual indication of how much time there is left before the process completes.

I know I can do something like printing more and more X's by adding them to the string and then simply printf, but that would look like:

 [XXXXXXX       ] 
 [XXXXXXXX      ] 
 [XXXXXXXXX     ] 
 [XXXXXXXXXX    ] 

or something like that (obviously you can play with the spacing.) But this is not visually aesthetic. Is there a way to update the printed text in a terminal with new text without reprinting? This is all under linux, c++.

 45  26931  45
1 Jan 1970

Solution

 52

try using \r instead of \n when printing the new "version".

for(int i=0;i<=100;++i) printf("\r[%3d%%]",i);
printf("\n");
2009-08-26

Solution

 13

I'd say that a library like ncurses would be used to such things. curses helps move the cursor around the screen and draw text and such.

NCurses

2009-08-26