I would like to create a small function, which should show the current status in percentage in the console. The function should only show the current value in the line. So I have to remove the last output. Is that possible? The best case would be some ANSI C stuff, the program should work on linux and windows.
I have found some escape sequences like "\033[J"
, but it dose not work.
Edit
Well I tried it with:
void PrintProcessBar(int i, int n) {
float ratio = i / (float)n;
printf("%.3d\b\b", (int)(ratio * 100));
fflush(stdout);
}
But it just print lots of zeros... What went wrong? If I use three \b
I get nothing.
Solution
float ratio = (i / (float)n) * 100;
printf("\b\b\b\b");
fflush(stdout);
printf("%.3d%c", (int)ratio, 37);
fflush(stdout);
i = current position. n = max runs.
I use 4 \b
because, at the first call of the function it will remove 4 spaces.
Greetz.
The interpretation of the backspace and carriage return characters is left to the software you use for display. A terminal emulator, when displaying \b would move the cursor one step back, and when displaying \r to the beginning of the line.
The general format is ESC[X where ESC is the ASCII escape char ( 0x1b ), and X is the command.
\b
is the escape sequence for backspace. you can use it with spaces to delete a line.
For example:
printf("98%");
fflush(stdout);
// sleep some time
printf("\b\b\b99%");
fflush(stdout);
This should print 98%, and then replace it with 99%.
What you look for is \r
it is Carriage Return. Makes the carriage go back to the beginning of the line. Do not use \n
as it will go down one line.
Because \r does not delete text but simply allows you to overwrite, you have to make sure you print enough text (spaces if you need) to clear your line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With