Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace already-printed text in the command prompt?

A lot of times I've seen text-based programs which replace text which has already been printed. For instance, imagine a program where the progress is printed as

Loading: 5%

and then it says

Loading: 10%

and so on, without printing new text which is appended?

How is this done? I haven't seen any such functions available in the library (in this case C). I have an idea, though: There is a character you can write which returns the prompt to the beginning of current line (\r I believe). Could this be used to "overwrite" what you've already printed to the command prompt?

like image 627
gablin Avatar asked Nov 25 '25 09:11

gablin


1 Answers

In most consoles, writing a bare carriage return \r without a newline after it will return the cursor to the beginning of the current line, allowing you to overwrite the existing text. Writing the backspace character \b also moves the cursor back one character.

For simple behavior, such as a progress indicator, this is all you need. For more complex behavior, you need to control the terminal through non-standard means. On Unix-based systems, the ncurses library can be used—it gives you full control over the cursor location, text color, keyboard echoing, more fine-grained keyboard input, and more.

On Windows, there's a suite of functions for manipulating consoles, and they can do mostly the same things as Unix consoles.

like image 58
Adam Rosenfield Avatar answered Nov 27 '25 01:11

Adam Rosenfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!