Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++.

like image 703
ldog Avatar asked Aug 26 '09 21:08

ldog


4 Answers

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

for(int i=0;i<=100;++i) printf("\r[%3d%%]",i);
printf("\n");
like image 98
Michael Krelin - hacker Avatar answered Nov 20 '22 03:11

Michael Krelin - hacker


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

like image 13
KFro Avatar answered Nov 20 '22 04:11

KFro


Something like this:

std::stringstream out;
for (int i = 0; i< 10; i++)
{
  out << "X";
  cout << "\r" << "[" << out.str() << "]";
}

The sneaky bit is the carriage return character "\r" which causes the cursor to move to the start of the line without going down to the next line.

like image 8
1800 INFORMATION Avatar answered Nov 20 '22 04:11

1800 INFORMATION


Others have already pointed out that you can use \r to go back to the beginning of the current line, and overwrite the entire line.

Another possibility is to use the backspace character ("\b") to erase a few spaces, and overwrite only those spaces. This can have a couple of advantages. First, it obviously avoids having to regenerate everything in the line, which can sometimes be mildly painful (though that is fairly unusual). Second, it can avoid some pain in displaying data that (for one example) shrinks in size as you write it -- for example, if you're displaying a count-down from 100 to 0, with \r you have to be careful about overwriting the entire previous length, or your countdown will go from (for example) 100 to 990 (i.e., leaving the previous "0" intact).

Note, however, that while back-space within a line normally works, a backspace at the beginning of a line may or may not move the cursor/write position back to a previous line. For most practical purposes, you can only move around within a single line.

like image 5
Jerry Coffin Avatar answered Nov 20 '22 03:11

Jerry Coffin