Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C remove printf output

Tags:

c

printf

console

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.

like image 610
Andre Hofmeister Avatar asked Feb 07 '12 10:02

Andre Hofmeister


People also ask

What is the use of B in C?

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.

How do you delete a line in C++?

The general format is ESC[X where ESC is the ASCII escape char ( 0x1b ), and X is the command.


2 Answers

\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%.

like image 100
MByD Avatar answered Sep 20 '22 23:09

MByD


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.

like image 37
Eregrith Avatar answered Sep 18 '22 23:09

Eregrith